﻿Imports System.IO
Imports System.Text

Public Class MainForm

    Private crcTextChanged, formIsReady As Boolean
    Private masterPacthes As String

    Private win As String = "32,33,221,35,36,37,38,253,40,41,42,43,225,45,254,47,48,49,50,51,52,53,54,55,56,57,198,230,193,61,222,63,64,212,200,209,194,211,192,207,208,216,206,203,196,220,210,217,199,201,202,219,197,195,204,214,215,205,223,245,92,250,94,95,96,244,232,241,226,243,224,239,240,248,238,235,228,252,242,249,231,233,234,251,229,227,236,246,247,237,255,213,124,218"
    Private dos As String = "32,33,157,35,36,37,38,237,40,41,42,43,161,45,238,47,48,49,50,51,52,53,54,55,56,57,134,166,129,61,158,63,64,148,136,145,130,147,128,143,144,152,142,139,132,156,146,153,135,137,138,155,133,131,140,150,151,141,159,229,92,234,94,95,96,228,168,225,162,227,160,175,224,232,174,171,164,236,226,233,167,169,170,235,165,163,172,230,231,173,239,240,124,154"

    Private keysDik As String() = {"None",
        "Escape", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace", "Tab",
        "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "Enter", "LCTRL",
        "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "`", "Left Shift", "\",
        "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "Right Shift", "*", "Left Alt", "Space", "CapsLock",
        "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "NumLock", "ScrollLock",
        "Num 7", "Num 8", "Num 9", "Subtract", "Num 4", "Num 5", "Num 6", "Add", "Num 1", "Num 2", "Num 3", "Num 0", "Decimal", "N/A", "N/A", "N/A", "F11", "F12",
        "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A",
        "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A",
        "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A",
        "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A",
        "Equals", "", "", "", "AT", "COLON", "_", "", "STOP", "AX", "UNLABELED",
        "", "", "", "", "Num Enter", "RCTRL", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "Comma", "", "Divide", "", "PrintScreen", "Right Alt", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "Home", "UpArrow", "PageUp", "", "LeftArrow", "", "RightArrow", "", "End", "DownArrow", "PageDown", "Insert", "Delete", "", "", "", "", "", "", "",
        "Left Win", "Right Win", "App Menu"
    }

    Public Sub New()
        MainCheck()
        InitializeComponent()

        Dim version = Application.ProductVersion
        Dim n = version.LastIndexOf("."c)
        Me.Text &= version.Remove(n) + " - by Mr.STALIN"

        'Дата релиза
        Dim releaseDate = New DateTime(2000, 1, 1).AddDays(My.Application.Info.Version.Build).AddSeconds(My.Application.Info.Version.Revision * 2).ToString
        labelRelease.Text = String.Format(labelRelease.Text, version, releaseDate.Remove(releaseDate.IndexOf(" "c)))

        If Not (File.Exists(AppPath & "\ddraw.ini")) Then
            For i = 0 To 3
                MainTabControl.TabPages.RemoveAt(0)
            Next
            btnRunGame.Enabled = False
            cbGameExe.Enabled = False
            Exit Sub
        End If

        ConfigFile.MainInitialization()
        Mods.LoadModsList()

        'Me.Text += " - Файл: " + If(sfallFile = Nothing, "ddraw.ini", sfallFile)

        tbGameConfig.Text = ConfigFile.cfgDefaultFile
        tbSfallConfig.Text = ConfigFile.sfallFile

        If (String.IsNullOrEmpty(ConfigFile.sfallFile)) Then btnMakeConfig.Enabled = True

        Dim cfgExe = ConfigFile.GetGameExe()
        cbGameExe.Items.Add(cfgExe)
        cbGameExe.SelectedIndex = 0
        cfgExe = cfgExe.ToUpper

        ' получаем список exe файлов
        For Each exeFile As String In Directory.GetFiles(AppPath, "*.exe", SearchOption.TopDirectoryOnly)
            Dim exe = Path.GetFileName(exeFile)
            If (cfgExe <> exe.ToUpper AndAlso exe <> AppDomain.CurrentDomain.FriendlyName AndAlso New FileInfo(exeFile).Length > 1024) Then
                cbGameExe.Items.Add(exe)
            End If
        Next

        Dim array = Resolution.GetResolution.ToArray()
        lstSfallResolution.Items.AddRange(array)

        btnRunGame.Enabled = CheckExePatchHRP(AppPath & "\" & cbGameExe.Text)

        GameTabsInitialization()

        If f2ResIni Is Nothing Then
            HiResTabControl.Enabled = False
            btnOpenHiResIni.Enabled = False
            lstResolutionHRP.Items.AddRange(array)
        Else
            HRPTabsInitialization()
        End If
        SfallTabsInitialization() ' не изменять положение

        ModsTabsInitialization()

    End Sub

    Private Sub MainForm_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
        If ddrawIni.Count = 0 Then
            DatDesc()
            MsgBox("Файл ddraw.ini не найден.")
        End If
        formIsReady = True
    End Sub

    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If lstSfallResolution.Items.Count Then SetSelectListResolution()
    End Sub

    Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyBase.FormClosing
        File.Delete(AppPath & "\dat.unp")
    End Sub

    Private Sub TabControl_Selecting(ByVal sender As Object, ByVal e As Windows.Forms.TabControlCancelEventArgs) Handles MainTabControl.Selecting
        Static onlyOnce As Boolean = False

        If e.TabPageIndex = 4 AndAlso onlyOnce = False Then
            onlyOnce = True
            DatDesc()
        End If
    End Sub

    Private Sub ListView1_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListView1.MouseDoubleClick
        InputDesc()
    End Sub

#Region " SFALL Tabs "

    Private Sub SfallTabsInitialization()
        CommonTab()
        InventoryTab()
        CombatTab()
        InterfaceTab()
        MiscTab()
        GraphicsTab()
        SystemTab()

        SmartAI()
    End Sub

    Private Sub CommonTab()

        Dim valueStr = ConfigFuncs.GetIniValue("[Highlighting]", "Key", sfModsIni) ' Mods
        If valueStr = Nothing Then
            valueStr = ConfigFuncs.GetConfigIniValue("ToggleItemHighlightsKey")
        End If
        If valueStr <> Nothing Then
            cbItemHighlightsKey.Enabled = True
            cbItemHighlightsKey.Checked = CBool(valueStr)

            Dim code As Byte = GetDecDXKeyCode(valueStr)
            If (code <> 0) Then highlightKeyCode = code

            btnHighlightKey.Text = keysDik(highlightKeyCode)
            btnHighlightKey.Enabled = cbItemHighlightsKey.Checked
        End If

        valueStr = ConfigFuncs.GetIniValue("[Highlighting]", "Containers", sfModsIni) ' Mods
        If valueStr = Nothing Then
            valueStr = ConfigFuncs.GetConfigIniValue("HighlightContainers")
            If valueStr = Nothing Then
                valueStr = ConfigFuncs.GetConfigIniValue("TurnHighlightContainers") ' Crafty
            End If
        End If
        If valueStr <> Nothing Then
            cbHighlightContainers.Enabled = cbItemHighlightsKey.Checked
            cbHighlightContainers.CheckState = CheckState.Unchecked
            cbHighlightContainers.Checked = CBool(valueStr)
        End If

        '  "Corpses"
        GetCheckerValue(cbCorpses, sfModsIni)
        cbCorpses.Enabled = cbItemHighlightsKey.Checked

        ' "NPCAutoLevel"
        GetCheckerValue(cbNPCAutoLevel)

        ' "DisplayKarmaChanges"
        GetCheckerValue(cbDisplayKarma)

        ' "EnableHeroAppearanceMod"
        GetCheckerValue(cbHeroAppearMod)

        ' "SpeedMultiInitial"
        If ConfigFuncs.GetSectionLineIndex("[Speed]") <> -1 Then GetNumberValue(nudSpeedMultiInit, 10, 1000)

        Select Case ConfigFuncs.GetConfigIniValue("TimeLimit")
            Case "0"
                cmbTimeLimit.SelectedIndex = 0
            Case "-1"
                cmbTimeLimit.SelectedIndex = 1
            Case "-2"
                cmbTimeLimit.SelectedIndex = 2
            Case "-3"
                cmbTimeLimit.SelectedIndex = 3
            Case Else
                cmbTimeLimit.SelectedIndex = 4
        End Select

        ' "DontTurnOffSneakIfYouRun"
        GetCheckerValue(cbDontTurnOffSneak)

        ' "UsePartySkills"
        GetCheckerValue(cbUsePartySkills, sfModsIni)

        ' "ShowInfoWindow"
        GetCheckerValue(cbShowInfoWindow, sfModsIni)

        ' "ActiveGeigerMsgs"
        GetCheckerValue(cbActiveGeigerMsgs)

        ' "AutoOpenDoor"
        GetCheckerValue(cbAutoOpenDoor, sfModsIni)

        valueStr = GetCheckerValue(cbExtraSaveSlots) ' "ExtraSaveSlots"
        If valueStr = Nothing Then
            cbExtraSaveSlots.Enabled = False
            cbExtraSaveSlots.Checked = True
        End If

        'valueStr = ConfigFuncs.GetConfigIniValue("AutoQuickSave")
        'If valueStr <> Nothing Then
        '    cmbQuickSave.Enabled = cbExtraSaveSlots.Checked
        '    cmbQuickSave.SelectedIndex = CInt(valueStr)
        'End If

        ' "AutoQuickSave"
        GetNumberValue(numQuickSavePages, 0, 999)
        numQuickSavePages.Enabled = cbExtraSaveSlots.Checked

        ' "AutoQuickSavePage"
        GetNumberValue(nudQuickSavePage, -1, 999)
        nudQuickSavePage.Enabled = cbExtraSaveSlots.Checked

        ' "AutoSave"
        If GetCheckerValue(cbAutoSave, sfModsIni) <> Nothing Then
            ' AutoSaveTime
            GetNumberValue(nudAutoSavePage, 0, 999, sfModsIni)
            Label37.Enabled = nudAutoSavePage.Enabled
            ' AutoSaveCountPages
            GetNumberValue(nudAutoSaveCountPages, 1, 100, sfModsIni)
            Label38.Enabled = nudAutoSaveCountPages.Enabled
            ' AutoSaveTime
            GetNumberValue(nudAutoSaveTime, 1, 999, sfModsIni)
            Label39.Enabled = nudAutoSaveTime.Enabled

            nudAutoSavePage.Enabled = cbAutoSave.Checked
            nudAutoSaveCountPages.Enabled = cbAutoSave.Checked
            nudAutoSaveTime.Enabled = cbAutoSave.Checked
        End If
    End Sub

    Private Sub CombatTab()
        cbSaveInCombat.SelectedIndex = ConfigFuncs.GetConfigIniValue("SaveInCombatFix")
        cmbDamageFormula.SelectedIndex = ConfigFuncs.GetConfigIniValue("DamageFormula")
        AmmoFileBox(cmbDamageFormula.SelectedIndex)

        Dim valueStr = ConfigFuncs.GetIniValue("[CombatControl]", "Key", sfModsIni)
        If valueStr <> Nothing Then
            cbToggleCombatKey.CheckState = CheckState.Unchecked
            cbToggleCombatKey.Enabled = True

            Dim code As Byte = Common.GetDecDXKeyCode(valueStr)
            cbToggleCombatKey.Checked = CBool(code)
            toggleCombatKeyCode = code

            btnToggleCombatKey.Enabled = cbToggleCombatKey.CheckState
            If code <> 0 Then btnToggleCombatKey.Text = keysDik(code)
        End If

        cmbControlCombat.SelectedIndex = 0
        valueStr = ConfigFuncs.GetIniValue("[CombatControl]", "Mode", sfModsIni) ' Mods
        If valueStr = Nothing Then valueStr = ConfigFuncs.GetConfigIniValue("ControlCombat") ' for 3.8

        If valueStr <> Nothing Then
            Dim index As Integer = CInt(valueStr)
            If (index > 0 AndAlso index < 5) Then
                cmbControlCombat.SelectedIndex = index
                cbToggleCombatKey.Enabled = (index = 2)
            End If
        End If

        valueStr = ConfigFuncs.GetConfigIniValue("FastShotFix")
        If valueStr <> Nothing Then
            cmbFastShotFix.Enabled = True
            cmbFastShotFix.SelectedIndex = CInt(valueStr)
        End If

        ' "ReloadWeaponKey"
        If GetCheckerValue(cbReloadWeapon) <> Nothing Then
            Dim code As Byte = GetDecDXKeyCode(ConfigFuncs.GetConfigIniValue(cbReloadWeapon.Tag.ToString))
            If (code <> 0) Then reloadWeaponKeyCode = code

            btnReloadSetKey.Enabled = cbReloadWeapon.Checked
            btnReloadSetKey.Text = keysDik(reloadWeaponKeyCode)
        End If

        ' "ComputeSprayMod"
        valueStr = ConfigFuncs.GetConfigIniValue(cbComputeSpray.Tag.ToString)
        If valueStr <> Nothing Then
            cbComputeSpray.Enabled = True
            cbComputeSpray.CheckState = CheckState.Unchecked
            cbComputeSpray.Checked = (valueStr = "2")
        End If

        ' "CheckWeaponAmmoCost"
        GetCheckerValue(cbWeaponAmmoCost)

        ' "ObjCanSeeObj_ShootThru_Fix"
        GetCheckerValue(cbObjCanSeeObj)

        ' "DisablePunchKnockback"
        GetCheckerValue(cbPunchKnockback)

        ' "TakeBetterWeapons"
        GetCheckerValue(cbTakeBetterWeapons)

        ' "SmartBehavior"
        GetCheckerValue(cbAISmartBehavior)

        ' "TryToFindTargets"
        GetCheckerValue(cbTryFindTarget)

        ' "LootingCorpses"
        GetCheckerValue(cbLootingCorpses)

        GetCheckerValue(cbNPCPushOnMoveBlock) ' NPCPushOnMoveBlock

        ' "HidingTactics"
        GetCheckerValue(cbHidingTactics)

        ' "AutoMoveToAttack"
        GetCheckerValue(cbAutoMoveToAttack)

        ' "NPCsTryToSpendExtraAP"
        GetNumberValue(nudNPCsTryToSpendExtraAP, 0, 100)

        valueStr = ConfigFuncs.GetConfigIniValue("CheckBurstFriendlyFire")
        If valueStr <> Nothing Then
            Dim val As Integer = CInt(valueStr)
            If val < 0 Then val = 4
            cmbCheckBurstFriendlyFire.SelectedIndex = val
            cmbCheckBurstFriendlyFire.Enabled = True
        End If

        '*** MODS ***

        ' "DropItemsOnDeath"
        GetCheckerValue(cbDropItemsOnDeath, sfModsIni)

        ' "DropItemsOnDeath"
        GetCheckerValue(cbCombatKeyMod, sfModsIni)

        ' GrenadeThrowing
        GetCheckerValue(cbGrenadeThrowing, sfModsIni)

        ' AccuracyMod
        GetCheckerValue(cbAccuracyMod, sfModsIni)

    End Sub

    Private Sub InventoryTab()

        ' "ItemFastMoveKey"
        If (GetCheckerValue(cbItemFastMoveKey) <> Nothing) Then
            Dim code As Byte = GetDecDXKeyCode(ConfigFuncs.GetConfigIniValue(cbItemFastMoveKey.Tag.ToString))
            If code <> 0 Then itemFastMoveKeyCode = code

            btnItemFastMoveSetKey.Enabled = cbItemFastMoveKey.Checked
            btnItemFastMoveSetKey.Text = keysDik(itemFastMoveKeyCode)
        End If

        ' "FastMoveFromContainer"
        GetCheckerValue(cbFastMoveContainer)

        ' "StackEmptyWeapons"
        GetCheckerValue(cbStackEmptyWeapons)

        ' "InstantWeaponEquip"
        GetCheckerValue(cbInstanWeaponEquip)

        ' "PartyMemberTakeOffItem"
        GetCheckerValue(cbPartyMemberTakeOffItem)

        ' "ItemCounterDefaultMax"
        GetCheckerValue(cbItemCounterDefaultMax)

        Dim valueStr As String = ConfigFuncs.GetConfigIniValue("ReloadReserve")
        If valueStr IsNot Nothing Then
            cmbReloadReserve.Enabled = True
            Select Case valueStr
                Case "-1"
                    cmbReloadReserve.SelectedIndex = 0
                Case "0"
                    cmbReloadReserve.SelectedIndex = 1
                Case "1"
                    cmbReloadReserve.SelectedIndex = 2
                Case Else
                    cmbReloadReserve.Text = valueStr
            End Select
        End If

        '*** Mods ***

        ' "PickupItemKey"
        If (GetCheckerValue(cbPickupItemKey, sfModsIni) <> Nothing) Then
            Dim code As Byte = Common.GetDecDXKeyCode(GetSectionKeyValue(cbPickupItemKey, sfModsIni))
            If code <> 0 Then pickupItemKeyCode = code

            btnPickupItemKey.Enabled = cbPickupItemKey.Checked
            btnPickupItemKey.Text = keysDik(pickupItemKeyCode)
        End If

        ' "QuickAmmoReload"
        GetCheckerValue(cbQuickAmmoReload, sfModsIni)

        ' "AutoCloseContainers"
        GetCheckerValue(cbAutoCloseContainers, sfModsIni)

        ' "CanSellUsedGeiger"
        GetCheckerValue(cbCanSellGeiger)

        ' "AutoReloadWeapon"
        GetCheckerValue(cbAutoReloadWeapon, sfModsIni)

    End Sub

    Private Sub InterfaceTab()

        ' "EnableMusicInDialogue"
        GetCheckerValue(cbMusicInDialogue)

        ' "NumbersInDialogue"
        GetCheckerValue(cbNumbersInDialogue)

        ' "UseScrollingQuestsList"
        Dim valueStr = GetCheckerValue(cbScrollingQuestsList)
        If valueStr <> Nothing Then
            cmbQuestButtonType.Enabled = cbScrollingQuestsList.Checked

            Dim val As Integer = CInt(valueStr)
            If (val > 0 AndAlso val < 3) Then
                cmbQuestButtonType.SelectedIndex = val - 1
            Else
                cmbQuestButtonType.SelectedIndex = 0
            End If

            GetNumberValue(nudQuestButtonX, 0, 640) ' QuestsScrollButtonsX
            GetNumberValue(nudQuestButtonY, 0, 480) ' QuestsScrollButtonsY

            nudQuestButtonX.Enabled = cbScrollingQuestsList.Checked
            nudQuestButtonY.Enabled = cbScrollingQuestsList.Checked
        End If

        ' "CombatPanelAnimDelay"
        GetNumberValue(nudCombatPanelAnimDelay, 0, 65535)

        ' "DialogPanelAnimDelay"
        GetNumberValue(nudDialogPanelAnimDelay, 0, 255)

        valueStr = ConfigFuncs.GetConfigIniValue("PipboyTimeAnimDelay")
        If valueStr <> Nothing Then
            cbPipboyTimeAnim.Enabled = True
            cbPipboyTimeAnim.CheckState = CheckState.Unchecked
            If CInt(valueStr) <= 25 Then cbPipboyTimeAnim.Checked = True
        End If

        valueStr = ConfigFuncs.GetConfigIniValue("ExpandWorldMap")
        If valueStr <> Nothing Then
            cmbExpWorldmap.Enabled = True
            cmbExpWorldmap.SelectedIndex = CInt(valueStr)
        End If

        ' "WideWorldmap"
        If (cmbExpWorldmap.Enabled AndAlso cmbExpWorldmap.SelectedIndex <> 0) Then GetCheckerValue(cbWideWorldmap)

        valueStr = ConfigFuncs.GetIniValue("[Misc]", "HideInterfaceKey", sfModsIni)
        If valueStr <> Nothing Then
            cbHideInterfaceKey.CheckState = CheckState.Unchecked
            cbHideInterfaceKey.Enabled = True

            Dim code As Byte = Common.GetDecDXKeyCode(valueStr)
            If code <> 0 Then hideInterfaceKeyCode = code
            cbHideInterfaceKey.Checked = CBool(code)

            btnHideInterfaceKey.Enabled = cbHideInterfaceKey.CheckState
            btnHideInterfaceKey.Text = keysDik(hideInterfaceKeyCode)
        End If

        ' "SpeedInterfaceCounterAnims"
        valueStr = GetCheckerValue(cbSpeedInterfaceCounter)
        If valueStr <> Nothing AndAlso valueStr = "3" Then cbSpeedInterfaceCounter.Checked = False

        ' "DisplayBonusDamage"
        GetCheckerValue(cbBonusDamage)

        ' "DisplayElectricalResist"
        GetCheckerValue(cbDisplayElectricalDmgStat)

        ' "PartyMemberExtraInfo"
        GetCheckerValue(cbPartyMemberExtraInfo)

        ' "WorldMapFontPatch"
        GetCheckerValue(cbWorldmapFontFix)

        ' "ActionPointsBar"
        GetCheckerValue(cbActionPointsBar)

        ' "ExpandInventory"
        GetCheckerValue(cbExpandInventory)

        GetCheckerValue(cbWorldMapTerrainInfo) ' WorldMapTerrainInfo

        GetCheckerValue(cbWorldMapTravelMarkers) ' WorldMapTravelMarkers

        GetCheckerValue(cbWorldmapTranslucency) ' WorldmapBlackTranslucency

    End Sub

    Private Sub MiscTab()
        Dim valueStr = ConfigFuncs.GetConfigIniValue("MotionScannerFlags")
        cmbMotionScannerFlags.SelectedIndex = CInt(valueStr) And &H3

        ' "UseWalkDistance"
        GetNumberValue(nudUseWalkDistance, 0, 3)

        ' "CorpseDeleteTime"
        GetNumberValue(nudCorpseDeleteTime, 0, 13)

        ' GhostPerkTweak
        GetCheckerValue(cbGhostPerkTweak)

        ' SmallFrameFix
        GetCheckerValue(сbSmallFrameFix)

        ' "RemoveCriticalTimelimits"
        GetCheckerValue(cbRemoveCriticalTime)

        ' "HeaveHoPerkTweak"
        GetCheckerValue(cbHeaveHoPerk, sfModsIni)

        ' "FadeBackgroundMusic"
        GetCheckerValue(cbFadeBackgroundMusic)

        ' "BackgroundDialogFX"
        GetCheckerValue(cbDialogFX, sfModsIni)

        '********** GRAFTY **********

        GetCheckerValue(cbFreeWeight) ' "FreeWeight"
        GetCheckerValue(cbEquipArmor) ' "EquipArmor"
        GetCheckerValue(cbPartySkills) ' "UsePartySkills"
        GetCheckerValue(cbCanSeeHear) ' "CanSeeAndHearFix"
        GetCheckerValue(cbDrugExploit) ' "DrugExploitFix"
        GetCheckerValue(cbOpenAndPassUnlockedDoors) ' "OpenAndPassUnlockedDoors"

        valueStr = ConfigFuncs.GetConfigIniValue("RiflescopePenalty")
        If valueStr <> Nothing Then
            nudRiflescopePenalty.Enabled = True
            nudRiflescopePenalty.Value = valueStr
        End If

        cbFadeMultiplier.Checked = (ConfigFuncs.GetConfigIniValue("FadeMultiplier") = "50")

        cbExplosionsEmitLight.Checked = CBool(ConfigFuncs.GetConfigIniValue("ExplosionsEmitLight"))

        GetNumberValue(nudAnimationsAtOnceLimit, 0, 127) ' "AnimationsAtOnceLimit"
    End Sub

    Private Sub GraphicsTab()
        Dim mode As Integer = CInt(ConfigFuncs.GetConfigIniValue("Mode"))
        If (mode > 0 AndAlso mode < 7) Then
            cmbMode.SelectedIndex = mode
            'lstSfallResolution.Enabled = True
            'nudResHeight.Enabled = True
            'nudResWidth.Enabled = True
            cbScale.Enabled = True
        Else
            cmbMode.SelectedIndex = 0
        End If

        nudResWidth.Value = ConfigFuncs.GetConfigIniValue("GraphicsWidth")
        nudResHeight.Value = ConfigFuncs.GetConfigIniValue("GraphicsHeight")

        If (f2ResIni IsNot Nothing) Then
            Dim width As Integer = nudWidthHRP.Value * 2
            Dim height As Integer = nudHeightHRP.Value * 2

            cbScale.Checked = (width = nudResWidth.Value AndAlso height = nudResHeight.Value)
        End If

        cbGPUBlt.Checked = (ConfigFuncs.GetConfigIniValue("GPUBlt") = "2")

        Dim valueStr = ConfigFuncs.GetConfigIniValue("TextureFilter")
        If valueStr <> Nothing Then
            cbTextureFilter.Enabled = True
            cbTextureFilter.CheckState = CheckState.Unchecked
            cbTextureFilter.Checked = If(valueStr = "2", True, False)
        End If

        GetCheckerValue(cbLimitFPS) ' "LimitFPS"

        Dim shadersPath As String
        If (masterPacthes IsNot String.Empty) Then
            shadersPath = Path.GetFullPath(masterPacthes + "\shaders\")
        Else
            shadersPath = AppPath + "\data\shaders\"
        End If

        If (Directory.Exists(shadersPath)) Then
            For Each fxFile As String In Directory.GetFiles(shadersPath, "*.fx", SearchOption.TopDirectoryOnly)
                cmbGlobalShaderFile.Items.Add(Path.GetFileName(fxFile))
            Next
        End If
        valueStr = ConfigFuncs.GetConfigIniValue(cmbGlobalShaderFile.Tag.ToString)
        If valueStr <> Nothing Then
            cmbGlobalShaderFile.Text = valueStr
        End If

    End Sub

    Private Sub SystemTab()
        Dim valueStr = ConfigFuncs.GetConfigIniValue("[Debugging]", "Enable")
        If valueStr <> Nothing Then
            cbSfallDebug.CheckState = CheckState.Unchecked
            cbSfallDebug.Checked = CBool(valueStr)
            cbSfallDebug.Enabled = True
        End If

        valueStr = ConfigFuncs.GetConfigIniValue("DebugMode")
        If valueStr <> Nothing Then
            cbDebugMode.Checked = CBool(valueStr)
            cmbDebugLog.Enabled = cbDebugMode.Checked
            cmbDebugLog.SelectedIndex = 1
            If cbDebugMode.Checked Then cmbDebugLog.SelectedIndex = CInt(valueStr) - 1
        End If

        GetCheckerValue(cbAllowUnsafe) ' "AllowUnsafeScripting"
        GetCheckerValue(cbSkipSize)    ' "SkipSizeCheck"

        valueStr = ConfigFuncs.GetConfigIniValue("ExtraCRC")
        If valueStr <> Nothing Then
            tbExtraCRC.Text = valueStr
        Else
            tbExtraCRC.Enabled = False
        End If

        cbProcessorIdle.Checked = (CInt(ConfigFuncs.GetConfigIniValue("ProcessorIdle")) <> -1)

        cbSingleCore.Checked = CBool(ConfigFuncs.GetConfigIniValue("SingleCore"))

        cbOverrideArtCacheSize.Checked = CBool(ConfigFuncs.GetConfigIniValue("OverrideArtCacheSize"))

        cbSkipOpeningMovies.Checked = CBool(ConfigFuncs.GetConfigIniValue("SkipOpeningMovies"))

        cbReverseMouseButtons.Checked = CBool(ConfigFuncs.GetConfigIniValue("ReverseMouseButtons"))

        numMouseSensitivity.Value = CDec(ConfigFuncs.GetConfigIniValue("MouseSensitivity"))

        valueStr = ConfigFuncs.GetConfigIniValue("XltKey")
        If valueStr <> Nothing Then
            cmbXltKey.Enabled = True
            cmbXltTable.Enabled = True

            Select Case valueStr
                Case "2"
                    cmbXltKey.SelectedIndex = 1
                Case "4"
                    cmbXltKey.SelectedIndex = 2
                Case Else
                    cmbXltKey.SelectedIndex = 0
            End Select

            Dim strLine() As String = ConfigFuncs.GetConfigIniValue("XltTable").Split(",")
            If strLine(2) = 221 Then
                cmbXltTable.SelectedIndex = 0
            Else
                cmbXltTable.SelectedIndex = 1
            End If
        End If

        valueStr = ConfigFuncs.GetConfigIniValue("SkipLoadingGameSettings")
        If valueStr <> Nothing Then
            cbSkipLoadingGameSetting.Enabled = True
            cbSkipLoadingGameSetting.CheckState = CheckState.Unchecked
            cbSkipLoadingGameSetting.Checked = If(valueStr = "2", True, False)
        End If

        GetCheckerValue(cbUseScrollWheel) ' "UseScrollWheel"

        valueStr = ConfigFuncs.GetConfigIniValue("NumSoundBuffers")
        If valueStr <> Nothing Then
            nudNumSoundBuffers.Value = If(valueStr <> "0", MaxMin(CInt(valueStr), 4, 32), 0)
        Else
            nudNumSoundBuffers.Enabled = False
        End If

        valueStr = ConfigFuncs.GetConfigIniValue("WindowScrollKey")
        If valueStr <> Nothing Then
            Select Case valueStr
                Case "-1"
                    btnWindowScrollKey.Text = "CTRL"
                Case "-2"
                    btnWindowScrollKey.Text = "ALT"
                Case "-3"
                    btnWindowScrollKey.Text = "SHIFT"
                Case Else
                    btnWindowScrollKey.Text = keysDik(CInt(valueStr))
            End Select
            Integer.TryParse(valueStr, windowScrollKeyCode)
        Else
            btnWindowScrollKey.Text = 0
        End If

        GetCheckerValue(cbBackgroundMouse) ' "BackgroundMouse"
    End Sub

#Region "* Control Common Tab *"

    Private Sub cbItemHighlightsKey_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbItemHighlightsKey.CheckedChanged
        If formIsReady Then
            cbItemHighlightsKey.ForeColor = SetColor("ToggleItemHighlightsKey", cbItemHighlightsKey.ForeColor)

            btnHighlightKey.Enabled = cbItemHighlightsKey.Checked

            If cbHighlightContainers.CheckState <> CheckState.Indeterminate Then cbHighlightContainers.Enabled = btnHighlightKey.Enabled
            If cbCorpses.CheckState <> CheckState.Indeterminate Then cbCorpses.Enabled = btnHighlightKey.Enabled

            Dim sVal = If(cbItemHighlightsKey.Checked, highlightKeyCode.ToString, "0") '42 shift key

            ConfigFuncs.SetConfigIniValue("ToggleItemHighlightsKey", sVal)
            ConfigFuncs.SetIniValue("[Highlighting]", "Key", sVal, sfModsIni)
        End If
    End Sub

    Private Sub btnHighlightKey_Click(sender As Object, e As EventArgs) Handles btnHighlightKey.Click
        SetKey_Click(sender, e)
        ConfigFuncs.SetIniValue("[Highlighting]", "Key", highlightKeyCode.ToString, sfModsIni)
    End Sub

    Private Sub cbHighlightContainers_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbHighlightContainers.CheckedChanged
        If formIsReady Then
            cbHighlightContainers.ForeColor = SetColor("HighlightContainers", cbHighlightContainers.ForeColor)

            Dim sVal = If(cbHighlightContainers.Checked, "1", "0")

            ConfigFuncs.SetConfigIniValue("HighlightContainers", sVal)
            ConfigFuncs.SetConfigIniValue("TurnHighlightContainers", sVal) ' это все еще нужно?

            Dim secKey() As String = Split(cbHighlightContainers.Tag.ToString, "|")
            ConfigFuncs.SetIniValue(secKey(0), secKey(1), sVal, sfModsIni)
        End If
    End Sub

    Private Sub cbCorpses_CheckedChanged(sender As Object, e As EventArgs) Handles cbCorpses.CheckedChanged
        If formIsReady Then
            cbCorpses.ForeColor = SetColor(cbCorpses.Tag.ToString, cbCorpses.ForeColor)

            Dim secKey() As String = Split(cbCorpses.Tag.ToString, "|")
            ConfigFuncs.SetIniValue(secKey(0), secKey(1), If(cbCorpses.Checked, "2", "0"), sfModsIni)
        End If
    End Sub

    Private Sub TimeLimit(ByVal sender As Object, ByVal e As EventArgs) Handles cmbTimeLimit.SelectionChangeCommitted
        Dim valLimit As Integer = 0
        Select Case cmbTimeLimit.SelectedIndex
            Case 1
                valLimit = -1
            Case 2
                valLimit = -2
            Case 3
                valLimit = -3
            Case 4
                valLimit = 13
        End Select
        ConfigFuncs.SetConfigIniValue("TimeLimit", valLimit)
    End Sub

    Private Sub nudSpeedMultiInit_Leave(sender As Object, e As EventArgs) Handles nudSpeedMultiInit.Leave
        SetNumberValue(nudSpeedMultiInit)
        ConfigFuncs.SetConfigIniValue("[Speed]", "Enable", "1")
    End Sub

    Private Sub cbAutoSave_CheckedChanged(sender As Object, e As EventArgs) Handles cbAutoSave.CheckedChanged
        If formIsReady Then
            If (cbAutoSave.Checked) Then
                cbExtraSaveSlots.Checked = True

                If (numQuickSavePages.Value = 0) Then
                    numQuickSavePages.Value = 1
                    SetSectionKeyValue(numQuickSavePages, 1, Nothing) ' "AutoQuickSave"
                End If
                'If (cmbQuickSave.SelectedIndex = 0) Then
                '    cmbQuickSave.SelectedIndex = 1
                '    SetSectionKeyValue(cmbQuickSave, 1, Nothing) ' "AutoQuickSave"
                'End If
            End If
            If (Label37.Enabled) Then nudAutoSavePage.Enabled = cbAutoSave.Checked
            If (Label38.Enabled) Then nudAutoSaveCountPages.Enabled = cbAutoSave.Checked
            If (Label39.Enabled) Then nudAutoSaveTime.Enabled = cbAutoSave.Checked
        End If
    End Sub

#End Region

#Region "* Control Combat Tab *"

    Private Sub cbComputeSpray_CheckedChanged(sender As Object, e As EventArgs) Handles cbComputeSpray.CheckedChanged
        If formIsReady Then
            cbComputeSpray.ForeColor = Common.SetColor(cbComputeSpray.Tag.ToString, cbComputeSpray.ForeColor)
            SetSectionKeyValue(cbComputeSpray, If(cbComputeSpray.Checked, "2", "0"), Nothing) ' "ComputeSprayMod"
        End If
    End Sub

    Private Sub FastShotFix(ByVal sender As Object, ByVal e As EventArgs) Handles cmbFastShotFix.SelectionChangeCommitted
        SetSectionKeyValue(cmbFastShotFix, cmbFastShotFix.SelectedIndex.ToString, Nothing) ' "FastShotFix"
    End Sub

    Private Sub ControlCombat(sender As Object, e As EventArgs) Handles cmbControlCombat.SelectionChangeCommitted
        Dim mode = cmbControlCombat.SelectedIndex

        If mode < 3 Then ConfigFuncs.SetConfigIniValue("ControlCombat", mode.ToString)
        SetSectionKeyValue(cmbControlCombat, mode.ToString, sfModsIni) ' "Mode"

        If (cbToggleCombatKey.CheckState <> CheckState.Indeterminate) Then
            cbToggleCombatKey.Enabled = (mode = 2)
            btnToggleCombatKey.Enabled = (cbToggleCombatKey.Enabled AndAlso cbToggleCombatKey.Checked)
        End If
    End Sub

    Private Sub ToggleCombatKey(sender As Object, e As EventArgs) Handles cbToggleCombatKey.CheckedChanged
        If formIsReady Then
            btnToggleCombatKey.Enabled = cbToggleCombatKey.Checked

            cbToggleCombatKey.ForeColor = Common.SetColor(cbToggleCombatKey.Tag.ToString, cbToggleCombatKey.ForeColor)

            SetSectionKeyValue(cbToggleCombatKey, If(cbToggleCombatKey.Checked, toggleCombatKeyCode.ToString, "0"), sfModsIni) ' "[CombatControl]" "Key"
        End If
    End Sub

    Private Sub btnToggleCombatKey_Click(sender As Object, e As EventArgs) Handles btnToggleCombatKey.Click
        Dim code As Integer

        If (InputKeyCodeForm.DXKeyCode(toggleCombatKeyCode.ToString, code)) Then
            If (code < 0) Then code = 0
            toggleCombatKeyCode = code
            btnToggleCombatKey.Text = keysDik(code)

            SetSectionKeyValue(cbToggleCombatKey, code.ToString, sfModsIni) ' "[CombatControl]" "Key"
        End If
    End Sub

    Private Sub ReloadWeapon(ByVal sender As Object, ByVal e As EventArgs) Handles cbReloadWeapon.CheckedChanged
        If formIsReady Then
            btnReloadSetKey.Enabled = cbReloadWeapon.Checked

            cbReloadWeapon.ForeColor = Common.SetColor(cbReloadWeapon.Tag.ToString, cbReloadWeapon.ForeColor)

            SetSectionKeyValue(cbReloadWeapon, If(cbReloadWeapon.Checked, reloadWeaponKeyCode.ToString, "0"), Nothing) '"ReloadWeaponKey"
        End If
    End Sub

    Private Sub SaveInCombat(ByVal sender As Object, ByVal e As EventArgs) Handles cbSaveInCombat.SelectionChangeCommitted
        SetSectionKeyValue(cbSaveInCombat, cbSaveInCombat.SelectedIndex.ToString, Nothing) ' "SaveInCombatFix"
    End Sub

    Private Sub CheckBurstFriendlyFire(sender As Object, e As EventArgs) Handles cmbCheckBurstFriendlyFire.SelectionChangeCommitted
        Dim val As Integer = cmbCheckBurstFriendlyFire.SelectedIndex
        If val = 4 Then val = -1
        SetSectionKeyValue(cmbCheckBurstFriendlyFire, val.ToString, Nothing) ' "CheckBurstFriendlyFire"
    End Sub

    Private Sub DamageFormula(ByVal sender As Object, ByVal e As EventArgs) Handles cmbDamageFormula.SelectionChangeCommitted
        Dim formula = cmbDamageFormula.SelectedIndex
        If formula = 3 Then formula = 0

        SetSectionKeyValue(cmbDamageFormula, formula.ToString, Nothing) '"DamageFormula"

        AmmoFileBox(formula)
    End Sub

    Private Sub AmmoFile(sender As Object, e As EventArgs) Handles tbxAmmoFile.Leave
        If (tbxAmmoFile.ReadOnly = False) Then ConfigFuncs.SetIniValue("[Misc]", tbxAmmoFile.Tag.ToString, tbxAmmoFile.Text.Trim, sfModsIni, True) ' изменяет закомментированное
    End Sub

    Private Sub AmmoFileBox(ByVal val As Byte)
        tbxAmmoFile.ReadOnly = True
        Select Case val
            Case 1, 2
                tbxAmmoFile.Text = "AmmoGlovz.ini"
            Case 5
                tbxAmmoFile.Text = "AmmoYAAM.ini"
            Case Else
                Dim file = ConfigFuncs.GetIniValue("[Misc]", tbxAmmoFile.Tag.ToString, sfModsIni) ' Получаем значение из опции AmmoFile
                If (IsNothing(file) = False) Then
                    tbxAmmoFile.Text = file
                Else
                    tbxAmmoFile.Clear()
                End If
                tbxAmmoFile.ReadOnly = False
        End Select
    End Sub

    Private Sub SmartAIBehavior(sender As Object, e As EventArgs) Handles cbAISmartBehavior.CheckedChanged
        If formIsReady Then
            SmartAI()
        End If
    End Sub

    Private Sub SmartAI()
        If cbAISmartBehavior.Enabled Then
            cbTakeBetterWeapons.Enabled = cbAISmartBehavior.Checked
            cbTryFindTarget.Enabled = cbAISmartBehavior.Checked
            If cbHidingTactics.CheckState <> CheckState.Indeterminate Then
                cbHidingTactics.Enabled = cbAISmartBehavior.Checked
            End If
        End If
    End Sub

#End Region

#Region "* Control Inventory Tab *"

    Private Sub ItemFastMoveKey(ByVal sender As Object, ByVal e As EventArgs) Handles cbItemFastMoveKey.CheckedChanged
        If formIsReady Then
            btnItemFastMoveSetKey.Enabled = cbItemFastMoveKey.Checked

            cbItemFastMoveKey.ForeColor = Common.SetColor(sender.Tag.ToString, cbItemFastMoveKey.ForeColor)

            SetSectionKeyValue(sender, If(cbItemFastMoveKey.Checked, itemFastMoveKeyCode.ToString, "0"), Nothing)
        End If
    End Sub

    Private Sub cbPickupItemKey_CheckedChanged(sender As Object, e As EventArgs) Handles cbPickupItemKey.CheckedChanged
        If formIsReady Then
            btnPickupItemKey.Enabled = cbPickupItemKey.Checked

            cbPickupItemKey.ForeColor = Common.SetColor(sender.Tag.ToString, cbPickupItemKey.ForeColor)

            SetSectionKeyValue(sender, If(cbPickupItemKey.Checked, pickupItemKeyCode.ToString, "0"), sfModsIni)
        End If
    End Sub

    Private Sub ReloadReserve(ByVal sender As Object, ByVal e As EventArgs) Handles cmbReloadReserve.TextChanged
        If formIsReady Then
            Dim sValue As String = cmbReloadReserve.Text
            Select Case cmbReloadReserve.SelectedIndex
                Case 0
                    sValue = "-1"
                Case 1
                    sValue = "0"
                Case 2
                    sValue = "1"
            End Select
            SetSectionKeyValue(cmbReloadReserve, sValue, Nothing) '"ReloadReserve"
        End If
    End Sub

#End Region

#Region "* Control Interface Tab *"

    Private Sub ExtraSaveSlots(ByVal sender As Object, ByVal e As EventArgs) Handles cbExtraSaveSlots.CheckedChanged
        If formIsReady Then
            SetSectionKeyValue(cbExtraSaveSlots, If(cbExtraSaveSlots.Checked, "1", "0"), Nothing)

            nudQuickSavePage.Enabled = cbExtraSaveSlots.Checked
            numQuickSavePages.Enabled = cbExtraSaveSlots.Checked 'cmbQuickSave.Enabled = cbExtraSaveSlots.Checked
        End If
    End Sub

    Private Sub QuickSave(ByVal sender As Object, ByVal e As EventArgs) Handles cmbQuickSave.SelectionChangeCommitted
        'SetSectionKeyValue(cmbQuickSave, cmbQuickSave.SelectedIndex.ToString, Nothing) ' "AutoQuickSave"
    End Sub

    Private Sub ExpWorldmap(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbExpWorldmap.SelectionChangeCommitted
        SetSectionKeyValue(cmbExpWorldmap, cmbExpWorldmap.SelectedIndex.ToString, Nothing) ' "ExpandWorldMap"

        cbWideWorldmap.Enabled = cmbExpWorldmap.SelectedIndex <> 0
    End Sub

    Private Sub PipboyTimeAnim(ByVal sender As Object, ByVal e As EventArgs) Handles cbPipboyTimeAnim.CheckedChanged
        If formIsReady Then
            cbPipboyTimeAnim.ForeColor = Common.SetColor(cbPipboyTimeAnim.Tag.ToString, cbPipboyTimeAnim.ForeColor)

            SetSectionKeyValue(cbPipboyTimeAnim, If(cbPipboyTimeAnim.Checked, "10", "50"), Nothing) ' "PipboyTimeAnimDelay"
        End If
    End Sub

    Private Sub SpeedInterfaceCounter(ByVal sender As Object, ByVal e As EventArgs) Handles cbSpeedInterfaceCounter.CheckedChanged
        If formIsReady Then
            cbSpeedInterfaceCounter.ForeColor = Common.SetColor(cbSpeedInterfaceCounter.Tag.ToString, cbSpeedInterfaceCounter.ForeColor)

            SetSectionKeyValue(cbSpeedInterfaceCounter, If(cbSpeedInterfaceCounter.Checked, "1", "3"), Nothing) '"SpeedInterfaceCounterAnims"
        End If
    End Sub

    Private Sub cbScrollingQuestsList_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbScrollingQuestsList.CheckedChanged
        If formIsReady Then
            'cbScrollingQuestsList.ForeColor = SetColor(cbScrollingQuestsList.Tag.ToString, 0)

            SetSectionKeyValue(cbScrollingQuestsList, If(cbScrollingQuestsList.Checked, (cmbQuestButtonType.SelectedIndex + 1).ToString, "0"), Nothing) '"UseScrollingQuestsList"

            cmbQuestButtonType.Enabled = cbScrollingQuestsList.Checked
            nudQuestButtonX.Enabled = cbScrollingQuestsList.Checked
            nudQuestButtonY.Enabled = cbScrollingQuestsList.Checked
        End If
    End Sub

    Private Sub QuestButtonType(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbQuestButtonType.SelectionChangeCommitted
        SetSectionKeyValue(cmbQuestButtonType, (cmbQuestButtonType.SelectedIndex + 1).ToString, Nothing) '"UseScrollingQuestsList"
    End Sub

    Private Sub cbHideInterfaceKey_CheckedChanged(sender As Object, e As EventArgs) Handles cbHideInterfaceKey.CheckedChanged
        If (formIsReady) Then
            btnHideInterfaceKey.Enabled = cbHideInterfaceKey.Checked

            cbHideInterfaceKey.ForeColor = Common.SetColor(sender.Tag.ToString, cbHideInterfaceKey.ForeColor)

            SetSectionKeyValue(sender, If(cbHideInterfaceKey.Checked, hideInterfaceKeyCode.ToString, "0"), sfModsIni)
        End If
    End Sub

    Private Sub btnHideInterfaceKey_Click(sender As Object, e As EventArgs) Handles btnHideInterfaceKey.Click
        Dim code As Integer

        If (InputKeyCodeForm.DXKeyCode(hideInterfaceKeyCode.ToString, code)) Then
            If (code < 0) Then code = 0
            hideInterfaceKeyCode = code
            btnHideInterfaceKey.Text = keysDik(code)

            SetSectionKeyValue(cbHideInterfaceKey, code.ToString, sfModsIni)
        End If
    End Sub

    Private Sub cbExpandInventory_CheckedChanged(sender As Object, e As EventArgs) Handles cbExpandInventory.CheckedChanged
        If formIsReady Then
            Dim cb As CheckBox = sender
            cb.ForeColor = Common.SetColor(cb.Tag.ToString, cb.ForeColor)

            SetSectionKeyValue(cb, If(cb.Checked, "2", "0"), Nothing)
        End If
    End Sub

#End Region

#Region "* Control Misc Tab *"

    Private Sub MotionScannerFlags(ByVal sender As Object, ByVal e As EventArgs) Handles cmbMotionScannerFlags.SelectedIndexChanged
        If formIsReady Then
            SetSectionKeyValue(cmbMotionScannerFlags, cmbMotionScannerFlags.SelectedIndex.ToString, Nothing)
        End If
    End Sub

    '*** Crafty ***
    Private Sub PartySkills(ByVal sender As CheckBox, ByVal e As EventArgs) Handles cbPartySkills.CheckedChanged
        If formIsReady Then
            cbPartySkills.ForeColor = Common.SetColor("UsePartySkillsCR", cbPartySkills.ForeColor)
            ConfigFuncs.SetConfigIniValue("UsePartySkills", If(cbPartySkills.Checked, "2", "0"))
        End If
    End Sub

    Private Sub FadeMultiplier(ByVal sender As Object, ByVal e As EventArgs) Handles cbFadeMultiplier.CheckedChanged
        If formIsReady Then
            cbFadeMultiplier.ForeColor = Common.SetColor(cbFadeMultiplier.Tag.ToString, cbFadeMultiplier.ForeColor)

            SetSectionKeyValue(cbFadeMultiplier, If(cbFadeMultiplier.Checked, "50", "100"), Nothing)
        End If
    End Sub
#End Region

#Region "* Control Graphics Tab *"

    Private Sub Mode(ByVal sender As Object, ByVal e As EventArgs) Handles cmbMode.SelectedIndexChanged
        If formIsReady Then
            Dim mode = cmbMode.SelectedIndex

            cbScale.Enabled = mode <> 0
            'lstSfallResolution.Enabled = cbScale.Enabled
            'nudResHeight.Enabled = lstSfallResolution.Enabled
            'nudResWidth.Enabled = lstSfallResolution.Enabled

            Dim secKey() As String = Split(cmbMode.Tag.ToString, "|")
            ConfigFuncs.SetIniValue(secKey(0), secKey(1), mode.ToString, ddrawIni)
            ConfigFuncs.SetIniValue(secKey(0), secKey(1), mode.ToString, sfallIni)
        End If
    End Sub

    Private Sub ResolutionList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstSfallResolution.SelectedIndexChanged
        If formIsReady Then
            Dim res As Resolution = lstSfallResolution.SelectedItem

            nudResWidth.Value = res.width
            nudResHeight.Value = res.height

            ResolutionChanged(Nothing, Nothing)
        End If
    End Sub

    Private Sub ResolutionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles nudResHeight.Leave, nudResWidth.Leave
        If (sender Is Nothing) Then
            SetNumberValue(nudResHeight) ' "GraphicsHeight"
            SetNumberValue(nudResWidth)  ' "GraphicsWidth"

            If (cbSetResToHRP.Checked = False) Then Return
        Else
            SetNumberValue(sender)
        End If

        Dim height As Integer = nudResHeight.Value
        Dim width As Integer = nudResWidth.Value

        If cbScale.Checked Then
            height /= 2
            width /= 2
        End If

        SetIniResolution_HRP(width, height)
        HRP_SetResolution(width, height)
    End Sub

    Private Sub cbScale_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbScale.CheckedChanged
        Resolution.ResolutionAddToList(cbScale.Checked, lstSfallResolution)

        If cbScale.Checked = False Then
            SetSelectListResolution()
            HRP_SetResolution(CInt(nudResWidth.Value), CInt(nudResHeight.Value))
            SetIniResolution_HRP(nudResWidth.Value, nudResHeight.Value)
            ToolTipRu.Hide(lstSfallResolution)
        Else
            ToolTipRu.Show("Теперь выберите требуемое разрешение.", lstSfallResolution, 20, -35, 3000)
        End If
    End Sub

    Private Sub GPUBlt(ByVal sender As Object, ByVal e As EventArgs) Handles cbGPUBlt.CheckedChanged
        If formIsReady Then
            cbGPUBlt.ForeColor = Common.SetColor(cbGPUBlt.Tag.ToString, cbGPUBlt.ForeColor)

            SetSectionKeyValue(cbGPUBlt, If(cbGPUBlt.Checked, "2", "0"), Nothing)
        End If
    End Sub

    Private Sub TextureFilter(ByVal sender As Object, ByVal e As EventArgs) Handles cbTextureFilter.CheckedChanged
        If formIsReady Then
            cbTextureFilter.ForeColor = Common.SetColor(cbTextureFilter.Tag.ToString, cbTextureFilter.ForeColor)

            SetSectionKeyValue(cbTextureFilter, If(cbTextureFilter.Checked, "2", "0"), Nothing)
        End If
    End Sub

    Private Sub cmbGlobalShaderFile_Leave(sender As Object, e As EventArgs) Handles cmbGlobalShaderFile.Leave
        SetSectionKeyValue(sender, cmbGlobalShaderFile.Text, Nothing)
    End Sub

#End Region

#Region "* Control System Tab *"

    Private Sub cbSfallDebug_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbSfallDebug.CheckedChanged
        If formIsReady Then
            cbSfallDebug.ForeColor = Common.SetColor(cbSfallDebug.Tag.ToString, cbSfallDebug.ForeColor)

            Dim secKey() As String = Split(cbSfallDebug.Tag.ToString, "|")
            ConfigFuncs.SetIniValue(secKey(0), secKey(1), If(cbSfallDebug.Checked, "1", "0"), sfallIni)
            ConfigFuncs.SetIniValue(secKey(0), secKey(1), If(cbSfallDebug.Checked, "1", "0"), ddrawIni)
        End If
    End Sub

    Private Sub DebugMode(ByVal sender As Object, ByVal e As EventArgs) Handles cbDebugMode.CheckedChanged
        If formIsReady Then
            cmbDebugLog.Enabled = cbDebugMode.Checked
            If cbDebugMode.Checked Then
                ConfigFuncs.SetIniValue("[Debugging]", "DebugMode", cmbDebugLog.SelectedIndex + 1, sfallIni)
                ConfigFuncs.SetIniValue("[Debugging]", "DebugMode", cmbDebugLog.SelectedIndex + 1, ddrawIni)
                SetDebugSection()
            Else
                ConfigFuncs.SetIniValue("[Debugging]", "DebugMode", "0", sfallIni)
                ConfigFuncs.SetIniValue("[Debugging]", "DebugMode", "0", ddrawIni)
            End If
        End If
    End Sub

    Private Sub DebugLog(ByVal sender As Object, ByVal e As EventArgs) Handles cmbDebugLog.SelectedIndexChanged
        If formIsReady Then
            ConfigFuncs.SetIniValue("[Debugging]", "DebugMode", cmbDebugLog.SelectedIndex + 1, sfallIni)
            ConfigFuncs.SetIniValue("[Debugging]", "DebugMode", cmbDebugLog.SelectedIndex + 1, ddrawIni)
        End If
    End Sub

    Private Sub ProcessorIdle(ByVal sender As Object, ByVal e As EventArgs) Handles cbProcessorIdle.CheckedChanged
        If formIsReady Then
            cbProcessorIdle.ForeColor = Common.SetColor(cbProcessorIdle.Tag.ToString, cbProcessorIdle.ForeColor)

            SetSectionKeyValue(cbProcessorIdle, If(cbProcessorIdle.Checked, "1", "-1"), Nothing)
        End If
    End Sub

    Private Sub SkipLoadingGameSetting(ByVal sender As Object, ByVal e As EventArgs) Handles cbSkipLoadingGameSetting.CheckedChanged
        If formIsReady Then
            cbSkipLoadingGameSetting.ForeColor = Common.SetColor(cbSkipLoadingGameSetting.Tag.ToString, cbSkipLoadingGameSetting.ForeColor)

            SetSectionKeyValue(cbSkipLoadingGameSetting, If(cbSkipLoadingGameSetting.Checked, "2", "1"), Nothing)
        End If
    End Sub

    Private Sub XltKey(ByVal sender As Object, ByVal e As EventArgs) Handles cmbXltKey.SelectedIndexChanged
        If formIsReady Then
            SetSectionKeyValue(cmbXltKey, If(cmbXltKey.SelectedIndex < 2, (cmbXltKey.SelectedIndex + 1).ToString, "4"), Nothing)
        End If
    End Sub

    Private Sub XltTable(ByVal sender As Object, ByVal e As EventArgs) Handles cmbXltTable.SelectedIndexChanged
        If formIsReady Then
            SetSectionKeyValue(cmbXltTable, If(cmbXltTable.SelectedIndex = 0, win, dos), Nothing)
        End If
    End Sub

    Private Sub nudNumSoundBuffers_Leave(sender As Object, e As EventArgs) Handles nudNumSoundBuffers.Leave
        If nudNumSoundBuffers.Value > 0 AndAlso nudNumSoundBuffers.Value < 4 Then nudNumSoundBuffers.Value = 0

        SetSectionKeyValue(nudNumSoundBuffers, nudNumSoundBuffers.Value.ToString, Nothing)
    End Sub

    Private Sub btnWindowScrollKey_Click(sender As Object, e As EventArgs) Handles btnWindowScrollKey.Click
        Dim code As Integer

        If (InputKeyCodeForm.DXKeyCode(windowScrollKeyCode.ToString, code)) Then
            Select Case code
                Case -1
                    btnWindowScrollKey.Text = "CTRL"
                Case -2
                    btnWindowScrollKey.Text = "ALT"
                Case -3
                    btnWindowScrollKey.Text = "SHIFT"
                Case Else
                    If (code < 0) Then code = 0
                    btnWindowScrollKey.Text = keysDik(code)
            End Select

            windowScrollKeyCode = code
            SetSectionKeyValue(btnWindowScrollKey, code.ToString, Nothing)
        End If
    End Sub

    Private Sub ExtraCRC_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbExtraCRC.TextChanged
        If formIsReady Then
            crcTextChanged = True
        End If
    End Sub

    Private Sub ExtraCRC_Leave(ByVal sender As Object, ByVal e As EventArgs) Handles tbExtraCRC.Leave
        If crcTextChanged Then SetIniCRC()

        crcTextChanged = False
    End Sub

#End Region

    ' Общие счекеры для ddraw.ini 0/1
    Private Sub CommonCheck_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbReverseMouseButtons.CheckedChanged, cbUseScrollWheel.CheckedChanged,
        cbSkipOpeningMovies.CheckedChanged, cbSingleCore.CheckedChanged, cbAllowUnsafe.CheckedChanged, cbSkipSize.CheckedChanged, cbExplosionsEmitLight.CheckedChanged,
        cbHeroAppearMod.CheckedChanged, cbOpenAndPassUnlockedDoors.CheckedChanged, cbFreeWeight.CheckedChanged, cbEquipArmor.CheckedChanged,
        cbDrugExploit.CheckedChanged, cbCanSeeHear.CheckedChanged, cbWorldmapFontFix.CheckedChanged, cbActionPointsBar.CheckedChanged, cbBonusDamage.CheckedChanged,
        cbDisplayElectricalDmgStat.CheckedChanged, cbWideWorldmap.CheckedChanged, cbFastMoveContainer.CheckedChanged, cbStackEmptyWeapons.CheckedChanged,
        cbInstanWeaponEquip.CheckedChanged, cbPartyMemberTakeOffItem.CheckedChanged, cbWeaponAmmoCost.CheckedChanged, cbAutoMoveToAttack.CheckedChanged,
        cbPunchKnockback.CheckedChanged, cbObjCanSeeObj.CheckedChanged, cbAISmartBehavior.CheckedChanged, cbTakeBetterWeapons.CheckedChanged,
        cbTryFindTarget.CheckedChanged, cbHidingTactics.CheckedChanged, cbNPCAutoLevel.CheckedChanged, cbDisplayKarma.CheckedChanged,
        cbDontTurnOffSneak.CheckedChanged, cbMusicInDialogue.CheckedChanged, cbCanSellGeiger.CheckedChanged, cbActiveGeigerMsgs.CheckedChanged,
        cbRemoveCriticalTime.CheckedChanged, cbNumbersInDialogue.CheckedChanged, cbLootingCorpses.CheckedChanged,
        cbItemCounterDefaultMax.CheckedChanged, cbOverrideArtCacheSize.CheckedChanged, cbPartyMemberExtraInfo.CheckedChanged, сbSmallFrameFix.CheckedChanged,
        cbWorldMapTerrainInfo.CheckedChanged, cbWorldMapTravelMarkers.CheckedChanged, cbNPCPushOnMoveBlock.CheckedChanged,
        cbLimitFPS.CheckedChanged, cbBackgroundMouse.CheckedChanged, cbFadeBackgroundMusic.CheckStateChanged, cbWorldmapTranslucency.CheckedChanged, cbGhostPerkTweak.CheckedChanged

        If formIsReady Then
            Dim cb As CheckBox = sender
            cb.ForeColor = Common.SetColor(cb.Tag.ToString, cb.ForeColor)

            SetSectionKeyValue(cb, If(cb.Checked, "1", "0"), Nothing)
        End If
    End Sub

    ' Чекеры для sfall-mods 0/1
    Private Sub ModsCommonCheck_CheckedChanged(sender As Object, e As EventArgs) Handles cbQuickAmmoReload.CheckedChanged, cbAutoCloseContainers.CheckedChanged, cbShowInfoWindow.CheckedChanged,
        cbCombatKeyMod.CheckedChanged, cbDropItemsOnDeath.CheckedChanged, cbUsePartySkills.CheckedChanged, cbAutoOpenDoor.CheckedChanged, cbAutoSave.CheckedChanged, cbHeaveHoPerk.CheckedChanged, cbDialogFX.CheckedChanged, cbGrenadeThrowing.CheckedChanged, cbAutoReloadWeapon.CheckedChanged, cbAccuracyMod.CheckedChanged

        If formIsReady Then
            Dim cb As CheckBox = sender
            cb.ForeColor = SetColor(cb.Tag.ToString, cb.ForeColor)

            SetSectionKeyValue(cb, If(cb.Checked, "1", "0"), sfModsIni)
        End If
    End Sub

    Private Sub CommonNumber_Leave(sender As Object, e As EventArgs) Handles nudUseWalkDistance.Leave, nudCorpseDeleteTime.Leave, nudNPCsTryToSpendExtraAP.Leave,
        nudDialogPanelAnimDelay.Leave, nudCombatPanelAnimDelay.Leave, nudRiflescopePenalty.Leave, nudAnimationsAtOnceLimit.Leave, numMouseSensitivity.Leave,
        nudQuestButtonY.Leave, nudQuestButtonX.Leave, nudQuickSavePage.Leave, numQuickSavePages.Leave

        SetNumberValue(sender)
    End Sub

    Private Sub ModsCommonNumber_Leave(sender As Object, e As EventArgs) Handles nudAutoSavePage.Leave, nudAutoSaveCountPages.Leave, nudAutoSaveTime.Leave
        SetNumberValue(sender, sfModsIni)
    End Sub

    Private Sub SetKey_Click(sender As Object, e As System.EventArgs) Handles btnItemFastMoveSetKey.Click, btnReloadSetKey.Click, btnPickupItemKey.Click
        Dim btn As Button = sender
        Dim cCode As Integer, mods As Boolean

        Select Case btn.Tag.ToString
            Case "ToggleItemHighlightsKey"
                cCode = highlightKeyCode
            Case "ReloadWeaponKey"
                cCode = reloadWeaponKeyCode
            Case "ItemFastMoveKey"
                cCode = itemFastMoveKeyCode
            Case "[Inventory]|PickupItemKey" ' Mods
                cCode = pickupItemKeyCode
                mods = True
            Case Else
                Exit Sub
        End Select

        Dim code As Integer
        If (InputKeyCodeForm.DXKeyCode(cCode.ToString, code)) Then
            If (code < 0) Then code = 0
            btn.Text = keysDik(code)

            SetSectionKeyValue(btn, code.ToString, If(mods, sfModsIni, Nothing))

            Select Case btn.Tag.ToString
                Case "ToggleItemHighlightsKey"
                    highlightKeyCode = code
                Case "ReloadWeaponKey"
                    reloadWeaponKeyCode = code
                Case "ItemFastMoveKey"
                    itemFastMoveKeyCode = code
                Case "[Inventory]|PickupItemKey"
                    pickupItemKeyCode = code
            End Select
        End If
    End Sub

    Private Function GetCheckerValue(ByRef control As CheckBox, Optional ByRef ini() As String = Nothing) As String
        Dim value As String = GetSectionKeyValue(control, ini)

        If (value <> Nothing) Then
            control.Enabled = True
            control.CheckState = CheckState.Unchecked
            control.Checked = CBool(value)
        End If

        Return value
    End Function

    Private Sub GetNumberValue(ByRef control As NumericUpDown, Optional ByVal min As Integer = -1, Optional ByVal max As Integer = -1, Optional ByRef ini() As String = Nothing)
        Dim value As String = GetSectionKeyValue(control, ini)

        If (IsNothing(value) = False) Then
            Dim iValue As Integer
            If (Integer.TryParse(value, iValue)) Then

                If (min <> -1 AndAlso max <> -1) Then
                    If (iValue < min) Then iValue = min
                    If (iValue > max) Then iValue = max
                End If

                control.Value = iValue
            Else
                SetSectionKeyValue(control, control.Value.ToString, ini) ' set default
            End If
            control.Enabled = True
        End If
    End Sub

    Private Sub SetNumberValue(ByRef control As NumericUpDown, Optional ByRef ini() As String = Nothing, Optional ByVal min As Integer = -1, Optional ByVal max As Integer = -1)
        Dim value As Integer = control.Value

        If (min <> -1 AndAlso max <> -1) Then
            If (value < min) Then value = min
            If (value > max) Then value = max

            control.Value = value
        End If

        SetSectionKeyValue(control, value.ToString, ini)
    End Sub

    ' Общая функция получения значения из ini
    Private Function GetSectionKeyValue(ByRef cntl As Control, ByRef ini() As String) As String
        If (ini Is Nothing) Then
            Return ConfigFuncs.GetConfigIniValue(cntl.Tag) ' sfall/ddraw.ini
        End If

        Dim secKey() As String = Split(cntl.Tag.ToString, "|")
        Return ConfigFuncs.GetIniValue(secKey(0), secKey(1), ini)
    End Function

    ' Общая функция записи значения в ini
    Private Sub SetSectionKeyValue(ByRef cntl As Control, ByVal setVal As String, ByRef ini() As String)
        If (ini Is Nothing) Then
            ConfigFuncs.SetConfigIniValue(cntl.Tag, setVal) ' sfall/ddraw.ini
            Return
        End If

        Dim secKey() As String = Split(cntl.Tag.ToString, "|")
        ConfigFuncs.SetIniValue(secKey(0), secKey(1), setVal, ini)
    End Sub

#End Region

    Private Sub btnMakeModConfig_Click(sender As Object, e As EventArgs) Handles btnMakeConfig.Click
        ConfigFile.MakeSfallIni()

        tbSfallConfig.Text = ConfigFile.sfallFile
        btnMakeConfig.Enabled = False
    End Sub

    Private Sub CheckCRC_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCheckCRC.Click
        OpenFileDialog.Filter = "exe files|*.exe"
        OpenFileDialog.InitialDirectory = AppPath
        OpenFileDialog.FileName = "FALLOUT2.EXE" 'default exe

        If OpenFileDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

        CheckExeCRC(OpenFileDialog.SafeFileName)
    End Sub

    Private Sub Merge_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMerge.Click
        OpenFileDialog.Filter = "ini files|*.ini"
        OpenFileDialog.InitialDirectory = AppPath

        If OpenFileDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

        Merge(OpenFileDialog.FileName, True)
        SfallTabsInitialization()
        MsgBox("Перенос настроек выполнен успешно!")
    End Sub


#Region " HRP Control "

    Private Sub HRPTabsInitialization()
        ResolutionTab()
        HPRInterfaceTab()
        ScreensTab()
        MapsTab()
        MiscOptionTab()
    End Sub

#Region " Resolution "

    Private Sub ResolutionTab()
        Dim scaleX2 = ConfigFuncs.GetStrValue("[MAIN]", "SCALE_2X", "0", f2ResIni)
        cbHRPScaleX2.Checked = CBool(scaleX2)

        Resolution.ResolutionAddToList(cbHRPScaleX2.Checked, lstResolutionHRP)

        Dim gMode = ConfigFuncs.GetStrValue("[MAIN]", "GRAPHICS_MODE", "2", f2ResIni)
        cmbHRPGraphicsMode.SelectedIndex = MaxMin(Integer.Parse(gMode, Globalization.NumberStyles.Integer), 0, 2)

        Dim WIDTH = ConfigFuncs.GetStrValue("[MAIN]", "SCR_WIDTH", "640", f2ResIni)
        Dim HEIGHT = ConfigFuncs.GetStrValue("[MAIN]", "SCR_HEIGHT", "480", f2ResIni)
        HRP_SetResolution(WIDTH, HEIGHT)

        Dim windowed = ConfigFuncs.GetStrValue("[MAIN]", "WINDOWED", "0", f2ResIni)
        If CBool(windowed) Then
            Dim fullwindowed = ConfigFuncs.GetStrValue("[MAIN]", "WINDOWED_FULLSCREEN", "0", f2ResIni)
            If CBool(fullwindowed) Then
                rbFullWindowed.Checked = True
            Else
                rbWindowed.Checked = True
            End If
        Else
            rbFullScreen.Checked = True
        End If

        Select Case ConfigFuncs.GetStrValue("[MAIN]", "COLOUR_BITS", "8", f2ResIni)
            Case "16"
                cmbHRPColorsBit.SelectedIndex = 1
            Case "24"
                cmbHRPColorsBit.SelectedIndex = 2
            Case "32"
                cmbHRPColorsBit.SelectedIndex = 3
            Case Else
                cmbHRPColorsBit.SelectedIndex = 0
        End Select
    End Sub

    Private Sub lstGameResolution_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstResolutionHRP.SelectedIndexChanged
        If formIsReady Then
            Dim res As Resolution = lstResolutionHRP.SelectedItem
            If res Is Nothing Then Exit Sub

            nudWidthHRP.Value = res.width
            nudHeightHRP.Value = res.height

            SetIniResolution_HRP(nudWidthHRP.Value.ToString, nudHeightHRP.Value.ToString)
        End If
    End Sub

    Private Sub cbHRPScaleX2_Click(sender As Object, e As EventArgs) Handles cbHRPScaleX2.CheckedChanged
        If formIsReady Then

            'lstResolutionHRP.Items.Clear()
            Resolution.ResolutionAddToList(cbHRPScaleX2.Checked, lstResolutionHRP)
            HRP_ListResolutionSelection(nudWidthHRP.Value.ToString, nudHeightHRP.Value.ToString) ' установить выделение

            If (cbHRPScaleX2.Checked AndAlso lstResolutionHRP.SelectedIndex = -1) Then
                Dim count = lstResolutionHRP.Items.Count - 1
                Dim res As Resolution = lstResolutionHRP.Items(count)

                HRP_SetResolution(res.width, res.height)
            End If
        End If
    End Sub

    Private Sub WidthHeightHRP_Leave(sender As Object, e As EventArgs) Handles nudWidthHRP.Leave, nudHeightHRP.Leave
        Dim nud As NumericUpDown = sender
        ConfigFuncs.SetIniValue("[MAIN]", nud.Tag.ToString, nud.Value, f2ResIni)
    End Sub

    Private Sub cmbHRPColorsBit_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbHRPColorsBit.SelectedIndexChanged
        If formIsReady Then ConfigFuncs.SetIniValue("[MAIN]", "COLOUR_BITS", cmbHRPColorsBit.Text, f2ResIni)
    End Sub

    Private Sub rbFullScreen_CheckedChanged(sender As Object, e As EventArgs) Handles rbFullScreen.CheckedChanged
        If formIsReady AndAlso rbFullScreen.Checked Then
            ConfigFuncs.SetIniValue("[MAIN]", "WINDOWED", "0", f2ResIni)
            ConfigFuncs.SetIniValue("[MAIN]", "WINDOWED_FULLSCREEN", "0", f2ResIni)
        End If
    End Sub

    Private Sub WindowedMode_CheckedChanged(sender As Object, e As EventArgs) Handles rbWindowed.CheckedChanged
        If formIsReady AndAlso rbWindowed.Checked Then
            ConfigFuncs.SetIniValue("[MAIN]", "WINDOWED", "1", f2ResIni)
            ConfigFuncs.SetIniValue("[MAIN]", "WINDOWED_FULLSCREEN", "0", f2ResIni)
        End If
    End Sub

    Private Sub rbFullWindowed_CheckedChanged(sender As Object, e As EventArgs) Handles rbFullWindowed.CheckedChanged
        If formIsReady AndAlso rbFullWindowed.Checked Then
            ConfigFuncs.SetIniValue("[MAIN]", "WINDOWED", "1", f2ResIni)
            ConfigFuncs.SetIniValue("[MAIN]", "WINDOWED_FULLSCREEN", "1", f2ResIni)
        End If
    End Sub

    Private Sub HRP_ListResolutionSelection(width As String, height As String)
        Dim res = width + " x " + height
        For i = 0 To lstResolutionHRP.Items.Count - 1
            If (lstResolutionHRP.Items(i).ToString = res) Then
                lstResolutionHRP.SelectedIndex = i
                Exit Sub
            End If
        Next
        lstResolutionHRP.SelectedIndex = -1
    End Sub

    Private Sub HRP_SetResolution(width As Integer, height As Integer)
        If (width = 0 OrElse height = 0) Then Exit Sub

        If (width < 640) Then width = 640
        If (height < 480) Then height = 480

        nudWidthHRP.Value = width
        nudHeightHRP.Value = height

        HRP_ListResolutionSelection(width.ToString, height.ToString)
    End Sub

    Private Sub HRP_SetResolution(width As String, height As String)
        HRP_SetResolution(MaxMin(Integer.Parse(width, Globalization.NumberStyles.Integer), 640, 10000), MaxMin(Integer.Parse(height, Globalization.NumberStyles.Integer), 480, 10000))
    End Sub
#End Region

#Region " Interface "

    Private barArtNum As Integer

    Private Sub HPRInterfaceTab()
        Dim state = ConfigFuncs.GetStrValue("[IFACE]", "IFACE_BAR_SIDES_ORI", "0", f2ResIni)
        cbBarSideOri.Checked = CBool(state)

        state = ConfigFuncs.GetStrValue("[OTHER_SETTINGS]", "DIALOG_SCRN_ART_FIX", "1", f2ResIni)
        cbDialogFixArt.Checked = CBool(state)

        nudBarWidth.Value = MaxMin(ConfigFuncs.GetIntValue("[IFACE]", "IFACE_BAR_WIDTH", 640, f2ResIni), 640, 10000)

        SetART(CInt(ConfigFuncs.GetIntValue("[IFACE]", cmbBarArt.Tag.ToString, 1, f2ResIni)))

        nudAmmoColorL.Value = MaxMin(ConfigFuncs.GetIntValue("[IFACE]", "ALTERNATE_AMMO_LIGHT", 196, f2ResIni), 0, 255)
        nudAmmoColorD.Value = MaxMin(ConfigFuncs.GetIntValue("[IFACE]", "ALTERNATE_AMMO_DARK", 75, f2ResIni), 0, 255)

        Select Case ConfigFuncs.GetStrValue("[IFACE]", "ALTERNATE_AMMO_METRE", "0", f2ResIni)
            Case "1"
                rbAmmoBarSingle.Checked = True
            Case "2"
                rbAmmoBarChanges.Checked = True
            Case "3"
                rbAmmoBarDivides.Checked = True
            Case Else
                rbAmmoBarDisable.Checked = True
        End Select

        state = ConfigFuncs.GetStrValue("[IFACE]", "IFACE_BAR_MODE", "0", f2ResIni)
        cbIfaceBarMode.Checked = CBool(state)
    End Sub

    Private Sub rbAmmoBar_Click(sender As Object, e As EventArgs) Handles rbAmmoBarDisable.Click, rbAmmoBarSingle.Click, rbAmmoBarChanges.Click, rbAmmoBarDivides.Click
        Dim rb As RadioButton = sender
        ConfigFuncs.SetIniValue("[IFACE]", "ALTERNATE_AMMO_METRE", rb.Tag.ToString, f2ResIni)
    End Sub

    Private Sub btnInc_Click(sender As Object, e As EventArgs) Handles btnInc.Click
        If (barArtNum < 99) Then SetART(barArtNum + 1)
    End Sub

    Private Sub btnDec_Click(sender As Object, e As EventArgs) Handles btnDec.Click
        If (barArtNum > 0) Then SetART(barArtNum - 1)
    End Sub

    Private Sub cmbBarArt_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbBarArt.SelectedIndexChanged
        If formIsReady AndAlso cmbBarArt.SelectedIndex < 3 Then SetART(cmbBarArt.SelectedIndex)
    End Sub

    Private Sub SetART(val As Integer)
        barArtNum = val
        tbBarArtNum.Text = barArtNum.ToString

        If barArtNum < 0 OrElse barArtNum > 2 Then
            cmbBarArt.SelectedIndex = 3
        Else
            cmbBarArt.SelectedIndex = barArtNum
        End If

        Select Case barArtNum
            Case 1
                pARTBox.Image = My.Resources.Resources.Metal
            Case 2
                pARTBox.Image = My.Resources.Resources.Leather
            Case Else
                pARTBox.Image = My.Resources.Resources.Black
        End Select

        ConfigFuncs.SetIniValue("[IFACE]", cmbBarArt.Tag.ToString, tbBarArtNum.Text, f2ResIni)
    End Sub

    Private Sub cbIfaceBarMode_CheckedChanged(sender As Object, e As EventArgs) Handles cbIfaceBarMode.CheckedChanged
        GroupBox16.Enabled = Not cbIfaceBarMode.Checked
    End Sub

#End Region

#Region " Screens "

    Private Sub ScreensTab()
        Dim num = CInt(ConfigFuncs.GetStrValue("[STATIC_SCREENS]", "SPLASH_SCRN_SIZE", "1", f2ResIni))
        cmbSplashScreen.SelectedIndex = MaxMin(num, 0, 2)

        num = CInt(ConfigFuncs.GetStrValue("[STATIC_SCREENS]", "DEATH_SCRN_SIZE", "1", f2ResIni))
        cmbDeathScreen.SelectedIndex = MaxMin(num, 0, 2)

        num = CInt(ConfigFuncs.GetStrValue("[STATIC_SCREENS]", "END_SLIDE_SIZE", "1", f2ResIni))
        cmbSlidersScreen.SelectedIndex = MaxMin(num, 0, 2)

        num = CInt(ConfigFuncs.GetStrValue("[STATIC_SCREENS]", "HELP_SCRN_SIZE", "0", f2ResIni))
        cmbHelpScreen.SelectedIndex = MaxMin(num, 0, 2)

        num = CInt(ConfigFuncs.GetStrValue("[MOVIES]", "MOVIE_SIZE", "1", f2ResIni))
        cmbMoviesScreen.SelectedIndex = MaxMin(num, 0, 2)

        num = CInt(ConfigFuncs.GetStrValue("[MAINMENU]", "MAIN_MENU_SIZE", "1", f2ResIni))
        cmbMainMenuScreen.SelectedIndex = MaxMin(num, 0, 2)

        num = ConfigFuncs.GetStrValue("[MAINMENU]", "MENU_BG_OFFSET_X", "-14", f2ResIni)
        nudMenuBGOffsetX.Value = MaxMin(Integer.Parse(num, Globalization.NumberStyles.Integer), -1000, 10000)

        num = ConfigFuncs.GetStrValue("[MAINMENU]", "MENU_BG_OFFSET_Y", "-4", f2ResIni)
        nudMenuBGOffsetY.Value = MaxMin(Integer.Parse(num, Globalization.NumberStyles.Integer), -1000, 10000)

        num = ConfigFuncs.GetStrValue("[OTHER_SETTINGS]", "SPLASH_SCRN_TIME", "1", f2ResIni)
        nudSplashTime.Value = MaxMin(Integer.Parse(num, Globalization.NumberStyles.Integer), 0, 10)

        Dim state = ConfigFuncs.GetStrValue("[MAINMENU]", "USE_HIRES_IMAGES", "1", f2ResIni)
        cbUseHiResImage.Checked = CBool(state)

        state = ConfigFuncs.GetStrValue("[MAINMENU]", "SCALE_BUTTONS_AND_TEXT_MENU", "0", f2ResIni)
        cbScaleButtons.Checked = CBool(state)

        state = ConfigFuncs.GetStrValue("[OTHER_SETTINGS]", "DIALOG_SCRN_BACKGROUND", "0", f2ResIni)
        cbDialogBackgroundScreen.Checked = CBool(state)
    End Sub

#End Region

#Region " Maps "

    Private Sub MapsTab()
        Dim num = ConfigFuncs.GetStrValue("[MAPS]", "NumPathNodes", "1", f2ResIni)
        trackPathNodes.Value = MaxMin(Integer.Parse(num, Globalization.NumberStyles.Integer), 1, 20)
        labelNumNodes.Text = (trackPathNodes.Value * 2000).ToString

        cbIgnorePCLimit.Checked = CBool(ConfigFuncs.GetStrValue("[MAPS]", "IGNORE_PLAYER_SCROLL_LIMITS", "0", f2ResIni))
        cbEddeClipping.Checked = CBool(ConfigFuncs.GetStrValue("[MAPS]", "EDGE_CLIPPING_ON", "1", f2ResIni))
        cbFogOfWar.Checked = CBool(ConfigFuncs.GetStrValue("[MAPS]", "FOG_OF_WAR", "0", f2ResIni))
    End Sub

    Private Sub trackPathNodes_Scroll(sender As Object, e As EventArgs) Handles trackPathNodes.Scroll
        labelNumNodes.Text = trackPathNodes.Value * 2000
        ConfigFuncs.SetIniValue("[MAPS]", "NumPathNodes", trackPathNodes.Value.ToString, f2ResIni)
    End Sub

#End Region

#Region " Misc "

    Private Sub MiscOptionTab()
        cbFixCPU.Checked = CBool(ConfigFuncs.GetStrValue("[OTHER_SETTINGS]", "CPU_USAGE_FIX", "0", f2ResIni))
        cbRecalculateFade.Checked = CBool(ConfigFuncs.GetStrValue("[OTHER_SETTINGS]", "FADE_TIME_RECALCULATE_ON_FADE", "0", f2ResIni))
        cbExtraWinMsg.Checked = CBool(ConfigFuncs.GetStrValue("[INPUT]", "EXTRA_WIN_MSG_CHECKS", "0", f2ResIni))

        txbDatFile.Text = ConfigFuncs.GetStrValue("[MAIN]", "f2_res_dat", "f2_res.dat", f2ResIni).ToLower
        txbPatchesFolder.Text = ConfigFuncs.GetStrValue("[MAIN]", "f2_res_patches", "data", f2ResIni).ToLower
    End Sub

    Private Sub txbDatFile_Leave(sender As Object, e As EventArgs) Handles txbDatFile.Leave
        ConfigFuncs.SetIniValue("[MAIN]", "f2_res_dat", txbDatFile.Text.Trim.ToLower, f2ResIni)
    End Sub

    Private Sub txbPatchesFolder_Leave(sender As Object, e As EventArgs) Handles txbPatchesFolder.Leave
        ConfigFuncs.SetIniValue("[MAIN]", "f2_res_patches", txbPatchesFolder.Text.Trim.ToLower, f2ResIni)
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        OpenFileFolderDialog.Filter = "Dat files|*.dat"
        OpenFileFolderDialog.InitialDirectory = If(txbDatFile.Text = String.Empty, AppPath, txbDatFile.Text)
        OpenFileFolderDialog.FileName = "f2_res"

        If OpenFileFolderDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

        Dim resFile = Common.MakeRelativePath(AppPath, OpenFileFolderDialog.FileName).ToLower
        txbDatFile.Text = resFile

        ConfigFuncs.SetIniValue("[MAIN]", "f2_res_dat", resFile, f2ResIni)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        FolderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer
        FolderBrowserDialog.Description = "Выберите папку в качестве директории для патча."
        FolderBrowserDialog.SelectedPath = If(txbPatchesFolder.Text = String.Empty, AppPath, txbPatchesFolder.Text)

        If FolderBrowserDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

        Dim folder = Common.MakeRelativePath(AppPath, FolderBrowserDialog.SelectedPath).ToLower 'Common.MakeRelativePath(FolderBrowserDialog.SelectedPath, AppPath).ToLower
        txbPatchesFolder.Text = folder

        ConfigFuncs.SetIniValue("[MAIN]", "f2_res_patches", folder, f2ResIni)
    End Sub

#End Region

    ' Общая функция для комбобоксов (индексы)
    Private Sub HRP_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSplashScreen.SelectedIndexChanged, cmbDeathScreen.SelectedIndexChanged,
        cmbSlidersScreen.SelectedIndexChanged, cmbHelpScreen.SelectedIndexChanged, cmbMoviesScreen.SelectedIndexChanged, cmbMainMenuScreen.SelectedIndexChanged,
        cmbHRPGraphicsMode.SelectedIndexChanged

        If formIsReady Then
            Dim cmb As ComboBox = sender
            Dim secKey() As String = Split(cmb.Tag.ToString, "|")
            ConfigFuncs.SetIniValue(secKey(0), secKey(1), cmb.SelectedIndex, f2ResIni)
        End If
    End Sub

    ' Общая функция для чекеров 0/1
    Private Sub HRP_CheckedChanged(sender As Object, e As EventArgs) Handles cbIgnorePCLimit.CheckedChanged, cbEddeClipping.CheckedChanged, cbUseHiResImage.CheckedChanged,
        cbScaleButtons.CheckedChanged, cbDialogBackgroundScreen.CheckedChanged, cbHRPScaleX2.CheckedChanged, cbExtraWinMsg.CheckedChanged,
        cbRecalculateFade.CheckedChanged, cbFixCPU.CheckedChanged, cbBarSideOri.CheckedChanged, cbDialogFixArt.CheckedChanged, cbIfaceBarMode.CheckedChanged, cbFogOfWar.CheckedChanged

        If formIsReady Then
            Dim cb As CheckBox = sender

            Dim state = If(cb.Checked, 1, 0)
            Dim secKey() As String = Split(cb.Tag.ToString, "|")

            ConfigFuncs.SetIniValue(secKey(0), secKey(1), state.ToString, f2ResIni)
        End If
    End Sub

    ' Общая функция для нумераторов
    Private Sub HRP_Leave(sender As Object, e As EventArgs) Handles nudMenuBGOffsetX.Leave, nudMenuBGOffsetY.Leave, nudAmmoColorL.Leave, nudAmmoColorD.Leave,
        nudBarWidth.Leave, nudSplashTime.Leave

        Dim nud As NumericUpDown = sender
        Dim secKey() As String = Split(nud.Tag.ToString, "|")
        ConfigFuncs.SetIniValue(secKey(0), secKey(1), nud.Value, f2ResIni)
    End Sub

    Private Sub ResMode_CheckedChanged(sender As Object, e As EventArgs) Handles rbSfallResMode.CheckedChanged, rbMashHRPMode.CheckedChanged
        If (formIsReady) Then
            btnEnable.Enabled = True
        Else
            If (rbMashHRPMode.Checked) Then
                rbMashHRPMode.ForeColor = Color.Green
                rbSfallResMode.ForeColor = Color.Black
                ' Активация HRP
            Else
                rbSfallResMode.ForeColor = Color.Green
                rbMashHRPMode.ForeColor = Color.Black
                ' Деактивация HRP
            End If
        End If

    End Sub

    Private Sub btnEnable_Click(sender As Object, e As EventArgs) Handles btnEnable.Click
        ConfigFuncs.SetConfigIniValue("[Main]", "HiResMode", If(rbSfallResMode.Checked, "1", "0"))

        If (rbMashHRPMode.Checked) Then
            ' Активация HRP
            rbMashHRPMode.ForeColor = Color.Green
            rbSfallResMode.ForeColor = Color.Black
        Else
            ' Деактивация HRP
            rbSfallResMode.ForeColor = Color.Green
            rbMashHRPMode.ForeColor = Color.Black
        End If

        Dim exe As String = AppPath & "\" & cbGameExe.Text
        If (Patcher.IsEnabledHRP(exe) <> rbMashHRPMode.Checked) Then
            Patcher.ToggleHiResPatch(exe, rbMashHRPMode.Checked)
        End If

        btnEnable.Enabled = False
    End Sub

#End Region

#Region " Other Control "

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles btnOpenModConfigFile.Click
        OpenFileDialog.Filter = "ini files|*.ini"
        OpenFileDialog.InitialDirectory = AppPath
        OpenFileDialog.FileName = ""

        If OpenFileDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

        SetCustomConfigFile(OpenFileDialog.FileName)
        tbSfallConfig.Text = ConfigFile.sfallFile

        SfallTabsInitialization()
    End Sub

    Private Sub btnOpenFalloutCFGFile_Click(sender As Object, e As EventArgs) Handles btnOpenFalloutCFGFile.Click
        OpenFileDialog.Filter = "cfg files|*.cfg"
        OpenFileDialog.InitialDirectory = AppPath
        OpenFileDialog.FileName = ""

        If OpenFileDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

        ConfigFile.SetGameCFGFile(OpenFileDialog.SafeFileName)
        tbGameConfig.Text = ConfigFile.cfgDefaultFile
    End Sub

    Private Function CheckExePatchHRP(exe As String) As Boolean
        btnEnable.Enabled = False

        Dim val = ConfigFuncs.GetConfigIniValue("HiResMode")
        If (val <> Nothing) Then
            rbSfallResMode.Checked = CBool(val)
            rbSfallResMode.Enabled = True
        End If

        Dim exists = File.Exists(exe)
        rbMashHRPMode.Enabled = exists AndAlso Patcher.CheckValid(exe)
        If (rbSfallResMode.Checked = False) Then rbMashHRPMode.Checked = (rbMashHRPMode.Enabled AndAlso Patcher.IsEnabledHRP(exe))

        Return exists
    End Function


    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    Private Sub cbGameExe_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbGameExe.SelectedIndexChanged
        If formIsReady Then
            SetGameExe(cbGameExe.Text)
            formIsReady = False
            btnRunGame.Enabled = CheckExePatchHRP(AppPath & "\" & cbGameExe.Text)
            formIsReady = True
        End If
    End Sub

    Private Sub RunGame_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRunGame.Click
        CheckExeCRC(cbGameExe.Text) ' выбранный exe в комбобоксе
        SaveAllConfigFiles()
        Process.Start(AppPath & "\" & cbGameExe.Text)
        Application.Exit()
    End Sub

    Private Sub OpenIni_Click(ByVal sender As Button, ByVal e As EventArgs) Handles btnOpenDdrawIni.Click, btnOpenHiResIni.Click, btnOpenModsIni.Click
        Dim ini = sender.Tag.ToString
        If (String.IsNullOrEmpty(ini)) Then
            ini = If(ConfigFile.sfallIni.Count, ConfigFile.sfallFile, "\ddraw.ini")
        Else
            If (ini = "sfall-mods") Then ini = sfallModsFile
        End If

        OpenConfig(ini)
    End Sub

    Private Sub CloseDone_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDone.Click
        SaveAllConfigFiles()
        Application.Exit()
    End Sub

    Private Sub LinkLabel1_LinkClicked(ByVal sender As Object, ByVal e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Process.Start("https://gitflic.ru/project/fakelshub/sfall/release")
    End Sub

#End Region

    Private Sub SetMasterPacthes(ByVal master As String)
        masterPacthes = master
    End Sub

    Private Sub GameTabsInitialization()
        cmbLanguage.Text = ConfigFuncs.GetStrValue("[system]", cmbLanguage.Tag.ToString, cfgGameData)

        TextBox1.Text = ConfigFuncs.GetStrValue("[system]", TextBox1.Tag.ToString, cfgGameData)
        TextBox2.Text = ConfigFuncs.GetStrValue("[system]", TextBox2.Tag.ToString, cfgGameData)
        TextBox3.Text = ConfigFuncs.GetStrValue("[system]", TextBox3.Tag.ToString, cfgGameData)
        TextBox4.Text = ConfigFuncs.GetStrValue("[system]", TextBox4.Tag.ToString, cfgGameData)

        TextBox5.Text = ConfigFuncs.GetStrValue("[sound]", TextBox5.Tag.ToString, cfgGameData)
        TextBox6.Text = ConfigFuncs.GetStrValue("[sound]", TextBox6.Tag.ToString, cfgGameData)

        SetMasterPacthes(TextBox2.Text)
    End Sub

    Private Sub cfgButtonPath_Click(sender As Object, e As EventArgs) Handles btnMasterDat.Click, btnMasterPatch.Click, btnCritterDat.Click, btnCritterPatch.Click, btnMusicPatch1.Click, btnMusicPatch2.Click
        Dim fileName As String = String.Empty
        Dim txtBox As TextBox = Nothing
        Dim type As Integer = CInt(CType(sender, Button).Tag)

        Select Case type
            Case 1
                fileName = "master"
                txtBox = TextBox1
            Case 2
                fileName = "master"
                txtBox = TextBox2
            Case 3
                fileName = "critter"
                txtBox = TextBox3
            Case 4
                fileName = "critter"
                txtBox = TextBox4
            Case 5
                fileName = "music"
                txtBox = TextBox5
            Case 6
                fileName = "music"
                txtBox = TextBox6
        End Select

        Dim selectPath As String = String.Empty

        If (type <= 4) Then
            OpenFileFolderDialog.Filter = "Dat files|*.dat"
            OpenFileFolderDialog.InitialDirectory = If(txtBox.Text = String.Empty, AppPath, txtBox.Text)
            OpenFileFolderDialog.FileName = fileName
            If OpenFileFolderDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

            selectPath = OpenFileFolderDialog.FileName
        Else
            FolderBrowserDialog.Description = "Выберите папку расположения музыки"
            FolderBrowserDialog.SelectedPath = If(txtBox.Text = String.Empty, AppPath, txtBox.Text)
            If FolderBrowserDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub

            selectPath = FolderBrowserDialog.SelectedPath + Path.DirectorySeparatorChar
        End If

        txtBox.Text = MakeRelativePath(AppPath, selectPath).ToLower

        If (type <= 4) Then
            ConfigFuncs.SetIniValue("[system]", txtBox.Tag.ToString, txtBox.Text, cfgGameData)
            If (txtBox.Tag.ToString = "master_patches") Then SetMasterPacthes(txtBox.Text)
        Else
            ConfigFuncs.SetIniValue("[sound]", txtBox.Tag.ToString, txtBox.Text, cfgGameData)
        End If
    End Sub

    Private Sub TextBox_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave, TextBox2.Leave, TextBox3.Leave, TextBox4.Leave
        Dim txtBox As TextBox = CType(sender, TextBox)
        ConfigFuncs.SetIniValue("[system]", txtBox.Tag.ToString, txtBox.Text, cfgGameData)
        If (txtBox.Tag.ToString = "master_patches") Then SetMasterPacthes(txtBox.Text)
    End Sub

    Private Sub TextBoxMusic_Leave(sender As Object, e As EventArgs) Handles TextBox5.Leave, TextBox6.Leave
        Dim txtBox As TextBox = CType(sender, TextBox)
        ConfigFuncs.SetIniValue("[sound]", txtBox.Tag.ToString, txtBox.Text, cfgGameData)
    End Sub

    Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged
        If (formIsReady) Then cfgSave = True
    End Sub

    Private Sub cmbLanguage_Leave(sender As Object, e As EventArgs) Handles cmbLanguage.Leave
        ConfigFuncs.SetIniValue("[system]", cmbLanguage.Tag.ToString, cmbLanguage.Text, cfgGameData)
        cfgSave = True
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        If (File.Exists(AppPath & cfgDefaultFile)) Then OpenConfig(cfgDefaultFile)
    End Sub


    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    Private Sub ModsTabsInitialization()
        ' "AutoloadingMods"
        GetCheckerValue(cbAutoLoadingMods)
        If (cbAutoLoadingMods.CheckState <> CheckState.Indeterminate) Then
            cbAutoLoadingMods.Checked = Not cbAutoLoadingMods.Checked
        End If

        Mods.GetOrderModsList(checkedModsList.Items)

        For Each item In Mods.GetAvaliableMods()
            lstDirectoryMods.Items.Add(item)
        Next

        If checkedModsList.Items.Count = 0 Then checkedModsList.Enabled = False

        If checkedModsList.Enabled Then
            Button5.Enabled = False
        End If

    End Sub

    Private Sub MoveModsItem1(mIndex As Integer)
        Dim cIndex = checkedModsList.SelectedIndex
        If (cIndex = -1 OrElse mIndex = cIndex) Then Return

        Mods.ModOrderLineTo(mIndex, cIndex)

        Dim moveItem = checkedModsList.Items.Item(mIndex)
        Dim moveItemState = checkedModsList.GetItemCheckState(mIndex)

        checkedModsList.Items.RemoveAt(mIndex)
        checkedModsList.Items.Insert(cIndex, moveItem)

        formIsReady = False
        checkedModsList.SetItemCheckState(cIndex, moveItemState)
        formIsReady = True

        checkedModsList.SelectedItem = moveItem
    End Sub

    Private Sub MoveModsItem(moveToIndex As Integer)
        Dim cIndex = checkedModsList.SelectedIndex
        If (cIndex = -1) Then Return

        Mods.ModOrderLineTo(cIndex, moveToIndex)

        Dim moveToItem = checkedModsList.Items.Item(moveToIndex)
        Dim cItem = checkedModsList.SelectedItem

        Dim moveToItemState = checkedModsList.GetItemCheckState(moveToIndex)
        Dim cItemState = checkedModsList.GetItemCheckState(cIndex)

        checkedModsList.Items.Item(moveToIndex) = cItem
        checkedModsList.Items.Item(cIndex) = moveToItem

        formIsReady = False
        checkedModsList.SetItemCheckState(cIndex, moveToItemState)
        checkedModsList.SetItemCheckState(moveToIndex, cItemState)
        formIsReady = True

        checkedModsList.SelectedItem = cItem
    End Sub

    Private moveIndex As Integer = -1
    Private clickLocation As Point
    Private clickDown As Boolean
    Private moveMouse As Boolean

    Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles checkedModsList.ItemCheck
        If (formIsReady = False) Then Return

        If e.CurrentValue = CheckState.Indeterminate Then
            e.NewValue = CheckState.Indeterminate
        Else
            Dim allowCheck = False
            If (clickLocation.X < 14) Then

                If clickLocation.Y < checkedModsList.Height - 12 Then
                    allowCheck = True
                End If
            End If
            If (allowCheck = False) Then
                e.NewValue = e.CurrentValue
            End If

            If (allowCheck) Then
                Mods.ModSetState(e.Index, e.NewValue)
            End If
        End If

    End Sub

    Private Sub btnUpMod_Click(sender As Object, e As EventArgs) Handles btnUpMod.Click
        If (checkedModsList.SelectedIndex > 0) Then
            MoveModsItem(checkedModsList.SelectedIndex - 1)
        End If
    End Sub

    Private Sub btnDnMod_Click(sender As Object, e As EventArgs) Handles btnDnMod.Click
        If (checkedModsList.SelectedIndex < checkedModsList.Items.Count - 1) Then
            MoveModsItem(checkedModsList.SelectedIndex + 1)
        End If
    End Sub

    Private Sub btnAddMod_Click(sender As Object, e As EventArgs) Handles btnAddMod.Click
        If (lstDirectoryMods.SelectedIndex = -1) Then Return

        If checkedModsList.Items.Count = 0 Then
            Button5.Enabled = False
            checkedModsList.Enabled = True
        End If

        Dim indx = checkedModsList.SelectedIndex
        If (indx <> -1) Then
            If (indx = checkedModsList.Items.Count - 1) Then indx = checkedModsList.Items.Count
        Else
            indx = checkedModsList.Items.Count
        End If

        Dim nameMod = lstDirectoryMods.Items(lstDirectoryMods.SelectedIndex)

        formIsReady = False
        checkedModsList.Items.Insert(indx, nameMod)
        checkedModsList.SetItemChecked(indx, True)
        formIsReady = True

        checkedModsList.SelectedIndex = indx

        Dim sIndx = lstDirectoryMods.SelectedIndex
        lstDirectoryMods.Items.RemoveAt(sIndx)
        If sIndx >= lstDirectoryMods.Items.Count Then sIndx -= 1
        lstDirectoryMods.SelectedIndex = sIndx

        Mods.AddMod(indx, nameMod)
    End Sub

    Private Sub btnDelMod_Click(sender As Object, e As EventArgs) Handles btnDelMod.Click
        If (checkedModsList.SelectedIndex = -1) Then Return

        Dim name = checkedModsList.Items(checkedModsList.SelectedIndex)

        Mods.RemoveMod(checkedModsList.SelectedIndex, "")

        ' удалить и переместить элемент
        Dim state = checkedModsList.GetItemCheckState(checkedModsList.SelectedIndex)
        If (state <> CheckState.Indeterminate) Then
            lstDirectoryMods.Items.Add(name) ' добавить
        End If
        checkedModsList.Items.RemoveAt(checkedModsList.SelectedIndex)
    End Sub

    Private Sub CheckedListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles checkedModsList.MouseDown
        clickLocation = e.Location

        If (e.Button = Windows.Forms.MouseButtons.Left) Then
            moveIndex = checkedModsList.SelectedIndex
            clickDown = True
        End If
    End Sub

    Private Sub checkedModsList_MouseMove(sender As Object, e As MouseEventArgs) Handles checkedModsList.MouseMove
        If clickDown = True AndAlso e.Button = Windows.Forms.MouseButtons.Left Then
            moveMouse = False
            Dim delta As Integer = e.Y - clickLocation.Y
            If (delta <> 0) Then moveMouse = True
        End If
    End Sub

    Private Sub checkedModsList_MouseUp(sender As Object, e As MouseEventArgs) Handles checkedModsList.MouseUp
        If (moveMouse = True AndAlso e.Button = Windows.Forms.MouseButtons.Left) Then
            MoveModsItem1(moveIndex)
            clickDown = False
            moveMouse = False
            moveIndex = -1
        End If
    End Sub

    Private Sub checkedModsList_KeyUp(sender As Object, e As KeyEventArgs) Handles checkedModsList.KeyUp
        If (e.Modifiers = Keys.Shift) Then
            If (e.KeyCode = Keys.Up OrElse e.KeyCode = Keys.Down) Then
                MoveModsItem1(moveIndex)
            End If
        End If
        moveIndex = -1
    End Sub

    Private Sub checkedModsList_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles checkedModsList.PreviewKeyDown
        If (moveIndex = -1) Then moveIndex = checkedModsList.SelectedIndex
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        Mods.OpenModsFile()
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Mods.CreateModsFile()

        formIsReady = False
        Mods.GetOrderModsList(checkedModsList.Items)
        formIsReady = True

        If checkedModsList.Items.Count Then
            Mods.LoadAutoMods()

            lstDirectoryMods.Items.Clear()
            For Each item In Mods.GetAvaliableMods()
                lstDirectoryMods.Items.Add(item)
            Next

            checkedModsList.Enabled = True
        End If

        Button5.Enabled = False
    End Sub

    Private Sub checkedModsList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles checkedModsList.SelectedIndexChanged
        If (checkedModsList.SelectedIndex = -1) Then
            btnDelMod.Enabled = False
            Return
        End If

        btnDelMod.Enabled = True

        Dim state = checkedModsList.GetItemCheckState(checkedModsList.SelectedIndex)
        If (state = CheckState.Indeterminate) Then
            btnDelMod.ImageIndex = 1
        Else
            btnDelMod.ImageIndex = 0
        End If
    End Sub

    Private Sub btbModsHelp_Click(sender As Object, e As EventArgs) Handles btbModsHelp.Click
        ToolTipRu.Show(ToolTipRu.GetToolTip(btbModsHelp), btbModsHelp, -50, 5, 3000)
    End Sub

    Private Sub cbAutoLoadingMods_CheckedChanged(sender As Object, e As EventArgs) Handles cbAutoLoadingMods.CheckedChanged
        If formIsReady Then
            Dim cb As CheckBox = sender
            cb.ForeColor = Common.SetColor(cb.Tag.ToString, cb.ForeColor)

            SetSectionKeyValue(cb, If(cb.Checked, "0", "1"), Nothing)
        End If
    End Sub

End Class
